/** X3DOM Runtime, http://www.x3dom.org/ 1.8.1 - 0c742a1a981f8c0a9cbb7059f36c3a6c4cb9fec6 - Fri Sep 27 18:22:15 2019 +0200 */ if(!Array.forEach){Array.forEach=function(array,fun,thisp){var len=array.length;for(var i=0;ix3dom.debug.maxLinesToLog){return;} var node=document.createElement("p");node.style.margin=0;switch(logType){case x3dom.debug.INFO:node.style.color="#00ff00";break;case x3dom.debug.WARNING:node.style.color="#cd853f";break;case x3dom.debug.ERROR:node.style.color="#ff4500";break;case x3dom.debug.EXCEPTION:node.style.color="#ffff00";break;default:node.style.color="#00ff00";break;} try{node.innerHTML=logType+": "+msg;x3dom.debug.logContainer.insertBefore(node,x3dom.debug.logContainer.firstChild);}catch(err){if(window.console.firebug!==undefined){window.console.warn(msg);}} if(x3dom.debug.isFirebugAvailable){switch(logType){case x3dom.debug.INFO:window.console.info(msg);break;case x3dom.debug.WARNING:window.console.warn(msg);break;case x3dom.debug.ERROR:window.console.error(msg);break;case x3dom.debug.EXCEPTION:window.console.debug(msg);break;default:break;}} x3dom.debug.numLinesLogged++;},logInfo:function(msg){x3dom.debug.doLog(msg,x3dom.debug.INFO);},logWarning:function(msg){x3dom.debug.doLog(msg,x3dom.debug.WARNING);},logError:function(msg){x3dom.debug.doLog(msg,x3dom.debug.ERROR);},logException:function(msg){x3dom.debug.doLog(msg,x3dom.debug.EXCEPTION);},assert:function(c,msg){if(!c){x3dom.debug.doLog("Assertion failed in "+ x3dom.debug.assert.caller.name+': '+ msg,x3dom.debug.ERROR);}},typeOf:function(obj){var type=typeof obj;return type==="object"&&!obj?"null":type;},exists:function(obj,name,type){type=type||"function";return(obj?this.typeOf(obj[name]):"null")===type;},dumpFields:function(node){var str="";for(var fName in node){str+=(fName+", ");} str+='\n';x3dom.debug.logInfo(str);return str;}};x3dom.debug.setup();x3dom.arc={};x3dom.arc.instance=null;x3dom.arc.Limits=function(min,max,initial) {this._min=min;this._max=max;this.getValue=function(value) {value=this._min+(this._max-this._min)*value;return this._max>=value?(this._min<=value?value:this._min):this._max;};};x3dom.arc.ARF=function(name,min,max,dirFac,factorGetterFunc,factorSetterFunc,getterFunc,setterFunc) {this._name=name;this._stateValue=[0.5,0.5];this._limits=new x3dom.arc.Limits(min,max);this._factorGetterFunc=factorGetterFunc;this._factorSetterFunc=factorSetterFunc;this._setterFunc=setterFunc;this._getterFunc=getterFunc;this._dirFac=dirFac;this.getFactor=function() {return this._factorGetterFunc();};this.update=function(state,step) {var stateVal=this._stateValue[state]+step*this._dirFac;this._stateValue[state]=0<=stateVal?(1>=stateVal?stateVal:1):0;this._setterFunc(this._limits.getValue(this._stateValue[state]));};this.reset=function() {this._stateValue[0]=0.5;this._stateValue[1]=0.5;};};x3dom.arc.AdaptiveRenderControl=defineClass(null,function(scene) {x3dom.arc.instance=this;this._scene=scene;this._targetFrameRate=[];this._targetFrameRate[0]=this._scene._vf.minFrameRate;this._targetFrameRate[1]=this._scene._vf.maxFrameRate;this._currentState=0;var that=this;var environment=that._scene.getEnvironment();this._arfs=[];this._arfs.push(new x3dom.arc.ARF("smallFeatureCulling",0,10,-1,function() {return environment._vf.smallFeatureFactor;},function(value) {environment._vf.smallFeatureFactor=value;},function() {return environment._vf.smallFeatureThreshold;},function(value) {environment._vf.smallFeatureThreshold=value;}));this._arfs.push(new x3dom.arc.ARF("lowPriorityCulling",0,100,1,function() {return environment._vf.lowPriorityFactor;},function(value) {environment._vf.lowPriorityFactor=value;},function() {return environment._vf.lowPriorityThreshold*100;},function(value) {environment._vf.lowPriorityThreshold=value/100;}));this._arfs.push(new x3dom.arc.ARF("tessellationDetailCulling",1,12,-1,function() {return environment._vf.tessellationErrorFactor;},function(value) {environment._vf.tessellationErrorFactor=value;},function() {return environment.tessellationErrorThreshold;},function(value) {environment.tessellationErrorThreshold=value;}));this._stepWidth=0.1;},{update:function(state,fps) {this._currentState=state;var delta=fps-this._targetFrameRate[state];this._stepWidth=Math.abs(delta)>10?0.1:0.01;var factorSum=0;var normFactors=[];var i,n=this._arfs.length;for(i=0;i0) factorSum+=normFactors[i];} var dirFac=delta<0?-1:1;for(i=0;i0) {normFactors[i]/=factorSum;this._arfs[i].update(state,this._stepWidth*normFactors[i]*dirFac);}}},reset:function() {for(var i=0,n=this._arfs.length;ithis.maxParallelRequests) {return;} var request=this.requests.pop();if(request) {this.activeRequests.push(request);request.send(null);this._sendRequest();}};x3dom.RequestManager._getCounters=function() {return{loaded:this.loadedRequests,active:this.activeRequests.length,failed:this.failedRequests,total:this.totalRequests,};};x3dom.RequestManager.addRequest=function(request) {if(!(request instanceof XMLHttpRequest)) {return;} this.totalRequests++;request.withCredentials=this.withCredentials;for(var i=0;i1) {var pixels=parts.colorMap.getPixels();for(i=0;i1) {var diffuseColors=[];for(i=0;i1) {var pixels=parts.emissiveMap.getPixels();for(i=0;i1) {var emissiveColors=[];for(i=0;i1) {var pixels=parts.specularMap.getPixels();for(i=0;i1) {var specularColors=[];for(i=0;i1) {var pixels=parts.colorMap.getPixels();for(i=0;i1) {var transparencies=[];for(i=0;i1) {var pixels=parts.specularMap.getPixels();for(i=0;i1) {var shininesses=[];for(i=0;i1) {var pixels=parts.emissiveMap.getPixels();for(i=0;i1) {var ambientIntensities=[];for(i=0;i1) {var hasChanged=false;var dtPixels=parts.colorMap.getPixels();var eaPixels=parts.emissiveMap.getPixels();var ssPixels=parts.specularMap.getPixels();dtColor=new x3dom.fields.SFColorRGBA(0,0,0,1.0);eaColor=new x3dom.fields.SFColorRGBA(color.r,color.g,color.b,0);ssColor=new x3dom.fields.SFColorRGBA(0,0,0,0);for(i=0;i1) {var hasChanged=false;var dtPixels=parts.colorMap.getPixels();var eaPixels=parts.emissiveMap.getPixels();var ssPixels=parts.specularMap.getPixels();for(i=0;i1) {var dtPixels=parts.colorMap.getPixels();var eaPixels=parts.emissiveMap.getPixels();var ssPixels=parts.specularMap.getPixels();for(i=0;i1)){x=parts.ids[0]%parts.colorMap.getWidth();y=Math.floor(parts.ids[0]/parts.colorMap.getWidth());var pixel=parts.visibilityMap.getPixel(x,y);visibilityAsInt=(visibility)?1:0;if(pixel.r!=visibilityAsInt){pixel.r=visibilityAsInt;this.multiPart._partVisibility[parts.ids[0]]=visibility;usage=this.multiPart._idMap.mapping[parts.ids[0]].usage;for(j=0;j0){visibleCount.val--;} if(visibleCount.val){this.multiPart._inlineNamespace.defMap[usage[j]]._vf.render=true;}else{this.multiPart._inlineNamespace.defMap[usage[j]]._vf.render=false;}} parts.visibilityMap.setPixel(x,y,pixel);this.multiPart.invalidateVolume();}} else {var hasChange=false;var pixels=parts.visibilityMap.getPixels();for(i=0;i0){visibleCount.val--;} if(visibleCount.val){this.multiPart._inlineNamespace.defMap[usage[j]]._vf.render=true;}else{this.multiPart._inlineNamespace.defMap[usage[j]]._vf.render=false;}}}} if(hasChange) {parts.visibilityMap.setPixels(pixels);this.multiPart.invalidateVolume();}}};this.getVolume=function(){var volume;var transmat=this.multiPart.getCurrentTransform();if(ids.length&&ids.length>1) {volume=new x3dom.fields.BoxVolume();for(var i=0;i1){node.prev.next=node.next;node.next.prev=node.prev;if(node==this.first){this.first=node.next;} if(node==this.last){this.last=node.prev;}}else{this.first=null;this.last=null;} node.prev=null;node.next=null;this.length--;};x3dom.DoublyLinkedList.prototype.getNode=function(index){var node=null;if(index>this.length){return node;} for(var i=0;i80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var i=dim;imaxX)maxX=x;if(y>maxY)maxY=y;} size=Math.max(maxX-minX,maxY-minY);} earcutLinked(outerNode,triangles,dim,minX,minY,size);if(clockwise===false){triangles.reverse();} return triangles;} function windingOrder(data,start,end,dim){var sum=0;var i,j;for(i=start,j=end-dim;i0;} function linkedList(data,start,end,dim,clockwise,oclockwise){var i,j,last;if(clockwise===oclockwise){for(i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);} return last;} function filterPoints(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)return null;again=true;}else{p=p.next;}}while(again||p!==end);return end;} function earcutLinked(ear,triangles,dim,minX,minY,size,pass){if(!ear)return;if(!pass&&size)indexCurve(ear,minX,minY,size);var stop=ear,prev,next;while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(size?isEarHashed(ear,minX,minY,size):isEar(ear)){triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);ear=next.next;stop=next.next;continue;} ear=next;if(ear===stop){if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,size,1);}else if(pass===1){ear=cureLocalIntersections(ear,triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,size,2);}else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,size);} break;}}} function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;var p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next;} return true;} function isEarHashed(ear,minX,minY,size){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;var minTX=a.xb.x?(a.x>c.x?a.x:c.x):(b.x>c.x?b.x:c.x),maxTY=a.y>b.y?(a.y>c.y?a.y:c.y):(b.y>c.y?b.y:c.y);var minZ=zOrder(minTX,minTY,minX,minY,size),maxZ=zOrder(maxTX,maxTY,minX,minY,size);var p=ear.nextZ;while(p&&p.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.nextZ;} p=ear.prevZ;while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;} return true;} function cureLocalIntersections(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);removeNode(p);removeNode(p.next);p=start=b;} p=p.next;}while(p!==start);return p;} function splitEarcut(start,triangles,dim,minX,minY,size){var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){var c=splitPolygon(a,b);a=filterPoints(a,a.next);c=filterPoints(c,c.next);earcutLinked(a,triangles,dim,minX,minY,size);earcutLinked(c,triangles,dim,minX,minY,size);return;} b=b.next;} a=a.next;}while(a!==start);} function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[],i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){qx=x;m=p.x=p.x&&p.x>=m.x&&pointInTriangle(hym.x))&&locallyInside(p,hole)){m=p;tanMin=tan;}} p=p.next;} return m;} function indexCurve(start,minX,minY,size){var p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,size);p.prevZ=p.prev;p.nextZ=p.next;p=p.next;}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p);} function sortLinked(list){var i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i0||(qSize>0&&q)){if(pSize===0){e=q;q=q.nextZ;qSize--;}else if(qSize===0||!q){e=p;p=p.nextZ;pSize--;}else if(p.z<=q.z){e=p;p=p.nextZ;pSize--;}else{e=q;q=q.nextZ;qSize--;} if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e;} p=q;} tail.nextZ=null;inSize*=2;}while(numMerges>1);return list;} function zOrder(x,y,minX,minY,size){x=32767*(x-minX)/size;y=32767*(y-minY)/size;x=(x|(x<<8))&0x00FF00FF;x=(x|(x<<4))&0x0F0F0F0F;x=(x|(x<<2))&0x33333333;x=(x|(x<<1))&0x55555555;y=(y|(y<<8))&0x00FF00FF;y=(y|(y<<4))&0x0F0F0F0F;y=(y|(y<<2))&0x33333333;y=(y|(y<<1))&0x55555555;return x|(y<<1);} function getLeftmost(start){var p=start,leftmost=start;do{if(p.x=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0;} function isValidDiagonal(a,b){return equals(a,b)||a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b);} function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y);} function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y;} function intersects(p1,q1,p2,q2){return area(p1,q1,p2)>0!==area(p1,q1,q2)>0&&area(p2,q2,p1)>0!==area(p2,q2,q1)>0;} function intersectsPolygon(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next;}while(p!==a);return false;} function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0;} function middleInside(a,b){var p=a,inside=false,px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{if(((p.y>py)!==(p.next.y>py))&&(px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x)) inside=!inside;p=p.next;}while(p!==a);return inside;} function splitPolygon(a,b){var a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2;} function insertNode(i,x,y,last){var p=new Node(i,x,y);if(!last){p.prev=p;p.next=p;}else{p.next=last.next;p.prev=last;last.next.prev=p;last.next=p;} return p;} function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ;} function Node(i,x,y){this.i=i;this.x=x;this.y=y;this.prev=null;this.next=null;this.z=null;this.prevZ=null;this.nextZ=null;this.steiner=false;}}} x3dom.FieldInterpolator=function(beginTime,endTime,beginValue,endValue) {this.beginTime=beginTime||0;this.endTime=endTime||1;this.beginValue=beginValue||0;this.endValue=endValue||0;this.isInterpolating=false;};x3dom.FieldInterpolator.prototype.isActive=function() {return(this.beginTime>0);};x3dom.FieldInterpolator.prototype.calcFraction=function(time) {var fraction=(time-this.beginTime)/(this.endTime-this.beginTime);return(Math.sin((fraction*Math.PI)-(Math.PI/2))+1)/2.0;};x3dom.FieldInterpolator.prototype.reset=function() {this.isInterpolating=false;this.beginTime=0;this.endTime=1;this.beginValue=0;this.endValue=0;};x3dom.FieldInterpolator.prototype.interpolate=function(time) {if(time=this.endTime) {var endValue=this.endValue;this.reset();return endValue;} else {this.isInterpolating=true;return this.beginValue+(this.endValue-this.beginValue)*this.calcFraction(time);}};x3dom.Utils={};x3dom.Utils.maxIndexableCoords=65535;x3dom.Utils.needLineWidth=false;x3dom.Utils.measurements=[];window.performance=window.performance||{};performance.now=(function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return new Date().getTime();};})();x3dom.Utils.startMeasure=function(name){var uname=name.toUpperCase();if(!x3dom.Utils.measurements[uname]){if(performance&&performance.now){x3dom.Utils.measurements[uname]=performance.now();}else{x3dom.Utils.measurements[uname]=new Date().getTime();}}};x3dom.Utils.stopMeasure=function(name){var uname=name.toUpperCase();if(x3dom.Utils.measurements[uname]){var startTime=x3dom.Utils.measurements[uname];delete x3dom.Utils.measurements[uname];if(performance&&performance.now){return performance.now()-startTime;}else{return new Date().getTime()-startTime;}} return 0;};x3dom.Utils.isNumber=function(n){return!isNaN(parseFloat(n))&&isFinite(n);};x3dom.Utils.createTexture2D=function(gl,doc,src,bgnd,crossOrigin,scale,genMipMaps,flipY) {flipY=flipY||false;var texture=gl.createTexture();var data=new Uint8Array([0,0,0,255,0,0,0,255,0,0,0,255,0,0,0,255]);gl.bindTexture(gl.TEXTURE_2D,texture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,2,2,0,gl.RGBA,gl.UNSIGNED_BYTE,data);if(genMipMaps){gl.generateMipmap(gl.TEXTURE_2D);} gl.bindTexture(gl.TEXTURE_2D,null);texture.ready=false;if(src==null||src=='') return texture;var image=new Image();switch(crossOrigin.toLowerCase()){case'anonymous':{image.crossOrigin='anonymous';}break;case'use-credentials':{image.crossOrigin='use-credentials';}break;case'none':{}break;default:{if(x3dom.Utils.forbiddenBySOP(src)){image.crossOrigin='anonymous';}}} image.src=src;doc.incrementDownloads();image.onload=function(){texture.originalWidth=image.width;texture.originalHeight=image.height;if(scale) image=x3dom.Utils.scaleImage(image);if(bgnd==true||flipY==true){gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);} gl.bindTexture(gl.TEXTURE_2D,texture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,image);if(genMipMaps){gl.generateMipmap(gl.TEXTURE_2D);} gl.bindTexture(gl.TEXTURE_2D,null);if(bgnd==true||flipY==true){gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,false);} texture.width=image.width;texture.height=image.height;texture.ready=true;doc.decrementDownloads();doc.needRender=true;};image.onerror=function(error) {x3dom.Utils.tryDDSLoading(texture,gl,doc,src,genMipMaps,flipY).then(function(){doc.decrementDownloads();doc.needRender=true;},function(){x3dom.debug.logError("[Utils|createTexture2D] Can't load Image: "+src);doc.decrementDownloads();});};return texture;};x3dom.Utils.tryDDSLoading=function(texture,gl,doc,src,genMipMaps,flipY) {return x3dom.DDSLoader.load(src).then(function(dds){if(!dds||(dds.isCompressed&&!x3dom.caps.COMPRESSED_TEXTURE)) {return;} gl.bindTexture(dds.type,texture);flipY=false;if(flipY) {gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);} if(!x3dom.Utils.isPowerOfTwo(dds.width)&&!x3dom.Utils.isPowerOfTwo(dds.height)) {gl.texParameteri(dds.type,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(dds.type,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(dds.type,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(dds.type,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);dds.generateMipmaps=false;} else if(dds.generateMipmaps) {gl.texParameteri(dds.type,gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR);} for(var target in dds.data) {var width=dds.width;var height=dds.height;var levels=dds.data[target];for(var l=0;l33779) {gl.texImage2D(+target,l,dds.format.internal,width,height,0,dds.format.format,dds.format.type,levels[l]);} else {gl.compressedTexImage2D(+target,l,dds.format.internal,width,height,0,levels[l]);dds.generateMipmaps=false;}}} if(dds.generateMipmaps) {gl.generateMipmap(dds.type);} if(flipY) {gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,false);} gl.bindTexture(dds.type,null);texture.width=dds.width;texture.height=dds.height;texture.ready=true;texture.textureCubeReady=true;});};x3dom.Utils.createTextureCube=function(gl,doc,src,bgnd,crossOrigin,scale,genMipMaps,flipY) {var data=new Uint8Array([0,0,0,255,0,0,0,255,0,0,0,255,0,0,0,255]);var texture=gl.createTexture();var faces;if(bgnd){faces=[gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_X,gl.TEXTURE_CUBE_MAP_NEGATIVE_X];} else {faces=[gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_X,gl.TEXTURE_CUBE_MAP_POSITIVE_X];} texture.ready=false;texture.pendingTextureLoads=-1;texture.textureCubeReady=false;var width=0,height=0;for(var i=0;i-1){filename=url.substr(url.lastIndexOf("/")+1);} else if(url.lastIndexOf("\\")>-1){filename=url.substr(url.lastIndexOf("\\")+1);} else{filename=url;} return filename;};x3dom.Utils.isWebGL2Enabled=function() {var canvas=document.createElement("canvas");var webgl2=canvas.getContext("webgl2")||canvas.getContext("experimental-webgl2");return(webgl2)?true:false;};x3dom.Utils.findTextureByName=function(texture,name) {for(var i=0;i>i;} return(x+1);};x3dom.Utils.nextBestPowerOfTwo=function(x) {var log2x=Math.log(x)/0.693147180559945;return Math.pow(2,Math.round(log2x));};x3dom.Utils.getDataTypeSize=function(type) {switch(type) {case"Int8":case"Uint8":return 1;case"Int16":case"Uint16":return 2;case"Int32":case"Uint32":case"Float32":return 4;case"Float64":default:return 8;}};x3dom.Utils.getOffsetMultiplier=function(indexType,gl) {switch(indexType) {case gl.UNSIGNED_SHORT:return 1;case gl.UNSIGNED_INT:return 2;case gl.UNSIGNED_BYTE:return 0.5;default:return 1;}};x3dom.Utils.getByteAwareOffset=function(offset,indexType,gl) {switch(indexType) {case gl.UNSIGNED_SHORT:return 2*offset;case gl.UNSIGNED_INT:return 4*offset;case gl.UNSIGNED_BYTE:return offset;default:return 2*offset;}};x3dom.Utils.getVertexAttribType=function(type,gl) {var dataType=gl.NONE;switch(type) {case"Int8":dataType=gl.BYTE;break;case"Uint8":dataType=gl.UNSIGNED_BYTE;break;case"Int16":dataType=gl.SHORT;break;case"Uint16":dataType=gl.UNSIGNED_SHORT;break;case"Int32":dataType=gl.INT;break;case"Uint32":dataType=gl.UNSIGNED_INT;break;case"Float32":dataType=gl.FLOAT;break;case"Float64":default:x3dom.debug.logError("Can't find this.gl data type for "+type+", getting FLOAT...");dataType=gl.FLOAT;break;} return dataType;};x3dom.Utils.getArrayBufferView=function(type,buffer) {var array=null;switch(type) {case"Int8":array=new Int8Array(buffer);break;case"Uint8":array=new Uint8Array(buffer);break;case"Int16":array=new Int16Array(buffer);break;case"Uint16":array=new Uint16Array(buffer);break;case"Int32":array=new Int32Array(buffer);break;case"Uint32":array=new Uint32Array(buffer);break;case"Float32":array=new Float32Array(buffer);break;case"Float64":array=new Float64Array(buffer);break;default:x3dom.debug.logError("Can't create typed array view of type "+type+", trying Float32...");array=new Float32Array(buffer);break;} return array;};x3dom.Utils.isUnsignedType=function(str) {return(str=="Uint8"||str=="Uint16"||str=="Uint16"||str=="Uint32");};x3dom.Utils.checkDirtyLighting=function(viewarea) {return(viewarea.getLights().length+viewarea._scene.getNavigationInfo()._vf.headlight);};x3dom.Utils.checkDirtyPhysicalEnvironmentLight=function(viewarea,shaderProperties) {return(!!shaderProperties.PHYSICALENVLIGHT!=viewarea.hasPhysicalEnvironmentLight());};x3dom.Utils.checkDirtyEnvironment=function(viewarea,shaderProperties) {var environment=viewarea._scene.getEnvironment();return(shaderProperties.GAMMACORRECTION!=environment._vf.gammaCorrectionDefault);};x3dom.Utils.minFilterDic=function(gl,minFilter) {switch(minFilter.toUpperCase()) {case"NEAREST":return gl.NEAREST;case"LINEAR":return gl.LINEAR;case"NEAREST_MIPMAP_NEAREST":return gl.NEAREST_MIPMAP_NEAREST;case"NEAREST_MIPMAP_LINEAR":return gl.NEAREST_MIPMAP_LINEAR;case"LINEAR_MIPMAP_NEAREST":return gl.LINEAR_MIPMAP_NEAREST;case"LINEAR_MIPMAP_LINEAR":return gl.LINEAR_MIPMAP_LINEAR;case"AVG_PIXEL":return gl.LINEAR;case"AVG_PIXEL_AVG_MIPMAP":return gl.LINEAR_MIPMAP_LINEAR;case"AVG_PIXEL_NEAREST_MIPMAP":return gl.LINEAR_MIPMAP_NEAREST;case"DEFAULT":return gl.LINEAR_MIPMAP_LINEAR;case"FASTEST":return gl.NEAREST;case"NEAREST_PIXEL":return gl.NEAREST;case"NEAREST_PIXEL_AVG_MIPMAP":return gl.NEAREST_MIPMAP_LINEAR;case"NEAREST_PIXEL_NEAREST_MIPMAP":return gl.NEAREST_MIPMAP_NEAREST;case"NICEST":return gl.LINEAR_MIPMAP_LINEAR;default:return gl.LINEAR;}};x3dom.Utils.minFilterDicX3D=function(minFilter) {switch(minFilter) {case 9728:return"NEAREST";case 9729:return"LINEAR";case 9984:return"NEAREST_MIPMAP_NEAREST";case 9985:return"LINEAR_MIPMAP_NEAREST";case 9986:return"NEAREST_MIPMAP_LINEAR";case 9987:return"LINEAR_MIPMAP_LINEAR";default:return"LINEAR_MIPMAP_LINEAR";}};x3dom.Utils.magFilterDic=function(gl,magFilter) {switch(magFilter.toUpperCase()) {case"NEAREST":return gl.NEAREST;case"LINEAR":return gl.LINEAR;case"AVG_PIXEL":return gl.LINEAR;case"DEFAULT":return gl.LINEAR;case"FASTEST":return gl.NEAREST;case"NEAREST_PIXEL":return gl.NEAREST;case"NICEST":return gl.LINEAR;default:return gl.LINEAR;}};x3dom.Utils.magFilterDicX3D=function(magFilter) {switch(magFilter) {case 9728:return"NEAREST";case 9729:return"LINEAR";default:return"LINEAR";}};x3dom.Utils.boundaryModesDicX3D=function(mode) {switch(mode) {case 10497:return"REPEAT";case 33071:return"CLAMP_TO_EDGE";case 33648:return"MIRRORED_REPEAT";default:return"REPEAT";}};x3dom.Utils.boundaryModesDic=function(gl,mode) {switch(mode.toUpperCase()) {case"CLAMP":return gl.CLAMP_TO_EDGE;case"CLAMP_TO_EDGE":return gl.CLAMP_TO_EDGE;case"CLAMP_TO_BOUNDARY":return gl.CLAMP_TO_EDGE;case"MIRRORED_REPEAT":return gl.MIRRORED_REPEAT;case"REPEAT":return gl.REPEAT;default:return gl.REPEAT;}};x3dom.Utils.primTypeDic=function(gl,type) {switch(type.toUpperCase()) {case"POINTS":return gl.POINTS;case"LINES":return gl.LINES;case"LINELOOP":return gl.LINE_LOOP;case"LINESTRIP":return gl.LINE_STRIP;case"TRIANGLES":return gl.TRIANGLES;case"TRIANGLESTRIP":return gl.TRIANGLE_STRIP;case"TRIANGLEFAN":return gl.TRIANGLE_FAN;default:return gl.TRIANGLES;}};x3dom.Utils.depthFunc=function(gl,func) {switch(func.toUpperCase()) {case"NEVER":return gl.NEVER;case"ALWAYS":return gl.ALWAYS;case"LESS":return gl.LESS;case"EQUAL":return gl.EQUAL;case"LEQUAL":return gl.LEQUAL;case"GREATER":return gl.GREATER;case"GEQUAL":return gl.GEQUAL;case"NOTEQUAL":return gl.NOTEQUAL;default:return gl.LEQUAL;}};x3dom.Utils.blendFunc=function(gl,func) {switch(func.toLowerCase()) {case"zero":return gl.ZERO;case"one":return gl.ONE;case"dst_color":return gl.DST_COLOR;case"dst_alpha":return gl.DST_ALPHA;case"src_color":return gl.SRC_COLOR;case"src_alpha":return gl.SRC_ALPHA;case"one_minus_dst_color":return gl.ONE_MINUS_DST_COLOR;case"one_minus_dst_alpha":return gl.ONE_MINUS_DST_ALPHA;case"one_minus_src_color":return gl.ONE_MINUS_SRC_COLOR;case"one_minus_src_alpha":return gl.ONE_MINUS_SRC_ALPHA;case"src_alpha_saturate":return gl.SRC_ALPHA_SATURATE;case"constant_color":return gl.CONSTANT_COLOR;case"constant_alpha":return gl.CONSTANT_ALPHA;case"one_minus_constant_color":return gl.ONE_MINUS_CONSTANT_COLOR;case"one_minus_constant_alpha":return gl.ONE_MINUS_CONSTANT_ALPHA;default:return 0;}};x3dom.Utils.blendEquation=function(gl,func) {switch(func.toLowerCase()) {case"func_add":return gl.FUNC_ADD;case"func_subtract":return gl.FUNC_SUBTRACT;case"func_reverse_subtract":return gl.FUNC_REVERSE_SUBTRACT;case"min":return 0;case"max":return 0;case"logic_op":return 0;default:return 0;}};x3dom.Utils.gunzip=function(arraybuffer) {var byteArray=new Uint8Array(arraybuffer);try{arraybuffer=new Zlib.Gunzip(byteArray).decompress().buffer;}catch(e){} return arraybuffer;};x3dom.Utils.generateProperties=function(viewarea,shape) {var property={};var geometry=shape._cf.geometry.node;var appearance=shape._cf.appearance.node;var texture=appearance?appearance._cf.texture.node:null;var material=appearance?appearance._cf.material.node:null;var environment=viewarea._scene.getEnvironment();if(appearance&&appearance._shader&&x3dom.isa(appearance._shader,x3dom.nodeTypes.ComposedShader)){property.CSHADER=appearance._shader._id;} else if(geometry){property.CSHADER=-1;property.APPMAT=(appearance&&(material||property.CSSHADER))?1:0;property.SOLID=(shape.isSolid())?1:0;property.TEXT=(x3dom.isa(geometry,x3dom.nodeTypes.Text))?1:0;property.POPGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.PopGeometry))?1:0;property.BUFFERGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.BufferGeometry))?1:0;property.IMAGEGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.ImageGeometry))?1:0;property.BINARYGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.BinaryGeometry))?1:0;property.EXTERNALGEOMETRY=(x3dom.isa(geometry,x3dom.nodeTypes.ExternalGeometry))?1:0;property.IG_PRECISION=(property.IMAGEGEOMETRY)?geometry.numCoordinateTextures():0;property.IG_INDEXED=(property.IMAGEGEOMETRY&&geometry.getIndexTexture()!=null)?1:0;property.POINTLINE2D=!geometry.needLighting()?1:0;property.VERTEXID=((property.BINARYGEOMETRY||property.EXTERNALGEOMETRY)&&geometry._vf.idsPerVertex)?1:0;property.IS_PARTICLE=(x3dom.isa(geometry,x3dom.nodeTypes.ParticleSet))?1:0;property.TANGENTDATA=(geometry._mesh._tangents[0].length>0&&geometry._mesh._binormals[0].length>0)?1:0;property.PBR_MATERIAL=(property.APPMAT&&x3dom.isa(material,x3dom.nodeTypes.PhysicalMaterial))?1:0;property.TWOSIDEDMAT=(property.APPMAT&&x3dom.isa(material,x3dom.nodeTypes.TwoSidedMaterial))?1:0;property.SEPARATEBACKMAT=(property.TWOSIDEDMAT&&material._vf.separateBackColor)?1:0;property.SHADOW=(viewarea.getLightsShadow())?1:0;property.FOG=(viewarea._scene.getFog()._vf.visibilityRange>0)?1:0;property.CSSHADER=(appearance&&appearance._shader&&x3dom.isa(appearance._shader,x3dom.nodeTypes.CommonSurfaceShader))?1:0;property.LIGHTS=(!property.POINTLINE2D&&appearance&&shape.isLit()&&(material||property.CSSHADER))?viewarea.getLights().length+(viewarea._scene.getNavigationInfo()._vf.headlight):0;property.TEXTURED=(texture||property.TEXT||(property.CSSHADER&&appearance._shader.needTexcoords())||(property.PBR_MATERIAL&&material.hasTextures()))?1:0;property.CUBEMAP=(texture&&x3dom.isa(texture,x3dom.nodeTypes.X3DEnvironmentTextureNode))||(property.CSSHADER&&appearance._shader.getEnvironmentMap())?1:0;property.PIXELTEX=(texture&&x3dom.isa(texture,x3dom.nodeTypes.PixelTexture))?1:0;property.TEXTRAFO=(appearance&&appearance._cf.textureTransform.node)?1:0;property.DIFFUSEMAP=(texture&&!x3dom.isa(texture,x3dom.nodeTypes.X3DEnvironmentTextureNode))||(property.CSSHADER&&appearance._shader.getDiffuseMap())||(property.PBR_MATERIAL&&material._cf.baseColorTexture.node)?1:0;property.NORMALMAP=(property.CSSHADER&&appearance._shader.getNormalMap())||(property.PBR_MATERIAL&&material._cf.normalTexture.node)?1:0;property.SPECMAP=(property.CSSHADER&&appearance._shader.getSpecularMap())?1:0;property.SHINMAP=(property.CSSHADER&&appearance._shader.getShininessMap())?1:0;property.EMISSIVEMAP=(property.PBR_MATERIAL&&material._cf.emissiveTexture.node)?1:0;property.OCCLUSIONMAP=(property.PBR_MATERIAL&&material._cf.occlusionTexture.node)?1:0;property.DISPLACEMENTMAP=(property.CSSHADER&&appearance._shader.getDisplacementMap())?1:0;property.DIFFPLACEMENTMAP=(property.CSSHADER&&appearance._shader.getDiffuseDisplacementMap())?1:0;property.MULTIDIFFALPMAP=(property.VERTEXID&&property.CSSHADER&&appearance._shader.getMultiDiffuseAlphaMap())?1:0;property.MULTIEMIAMBMAP=(property.VERTEXID&&property.CSSHADER&&appearance._shader.getMultiEmissiveAmbientMap())?1:0;property.MULTISPECSHINMAP=(property.VERTEXID&&property.CSSHADER&&appearance._shader.getMultiSpecularShininessMap())?1:0;property.MULTIVISMAP=(property.VERTEXID&&property.CSSHADER&&appearance._shader.getMultiVisibilityMap())?1:0;property.ALPHAMODE=(property.PBR_MATERIAL)?material._vf.alphaMode:"BLEND";property.ISROUGHNESSMETALLIC=(property.PBR_MATERIAL&&material._vf.model=="roughnessMetallic")?1:0;property.ROUGHNESSMETALLICMAP=(property.PBR_MATERIAL&&material._cf.roughnessMetallicTexture.node)?1:0;property.SPECULARGLOSSINESSMAP=(property.PBR_MATERIAL&&material._cf.specularGlossinessTexture.node)?1:0;property.OCCLUSIONROUGHNESSMETALLICMAP=(property.PBR_MATERIAL&&material._cf.occlusionRoughnessMetallicTexture.node)?1:0;property.PHYSICALENVLIGHT=viewarea.hasPhysicalEnvironmentLight()?1:0;property.NORMALSPACE=(property.NORMALMAP&&property.CSSHADER)?appearance._shader._vf.normalSpace.toUpperCase():(property.NORMALMAP&&property.PBR_MATERIAL)?material._vf.normalSpace.toUpperCase():"TANGENT";property.BLENDING=(property.TEXT||property.CUBEMAP||property.CSSHADER||(property.PBR_MATERIAL)||(texture&&texture._blending))?1:0;property.REQUIREBBOX=(geometry._vf.coordType!==undefined&&geometry._vf.coordType!="Float32")?1:0;property.REQUIREBBOXNOR=(geometry._vf.normalType!==undefined&&geometry._vf.normalType!="Float32")?1:0;property.REQUIREBBOXCOL=(geometry._vf.colorType!==undefined&&geometry._vf.colorType!="Float32")?1:0;property.REQUIREBBOXTEX=(geometry._vf.texCoordType!==undefined&&geometry._vf.texCoordType!="Float32")?1:0;property.COLCOMPONENTS=geometry._mesh._numColComponents;property.NORCOMPONENTS=geometry._mesh._numNormComponents;property.POSCOMPONENTS=geometry._mesh._numPosComponents;property.SPHEREMAPPING=(geometry._cf.texCoord!==undefined&&geometry._cf.texCoord.node!==null&&geometry._cf.texCoord.node._vf.mode&&geometry._cf.texCoord.node._vf.mode.toLowerCase()=="sphere")?1:0;property.VERTEXCOLOR=(geometry._mesh._colors[0].length>0||(property.IMAGEGEOMETRY&&geometry.getColorTexture())||(property.POPGEOMETRY&&geometry.hasColor())||(property.BUFFERGEOMETRY&&geometry.hasColor())||(geometry._vf.color!==undefined&&geometry._vf.color.length>0))?1:0;property.CLIPPLANES=shape._clipPlanes.length;property.ALPHATHRESHOLD=(appearance)?appearance._vf.alphaClipThreshold.toFixed(2):0.1;property.MULTITEXCOORD=(property.BUFFERGEOMETRY&&geometry.hasMultiTexCoord())?1:0;property.DIFFUSEMAPCHANNEL=(property.PBR_MATERIAL&&property.DIFFUSEMAP&&material._cf.baseColorTexture.node._vf.channel===1)?1:0;property.NORMALMAPCHANNEL=(property.PBR_MATERIAL&&property.NORMALMAP&&material._cf.normalTexture.node._vf.channel===1)?1:0;property.EMISSIVEMAPCHANNEL=(property.PBR_MATERIAL&&property.EMISSIVEMAP&&material._cf.emissiveTexture.node._vf.channel===1)?1:0;property.OCCLUSIONMAPCHANNEL=(property.PBR_MATERIAL&&property.OCCLUSIONMAP&&material._cf.occlusionTexture.node._vf.channel===1)?1:0;property.ROUGHNESSMETALLICMAPCHANNEL=(property.PBR_MATERIAL&&property.ROUGHNESSMETALLICMAP&&material._cf.roughnessMetallicTexture.node._vf.channel===1)?1:0;property.OCCLUSIONROUGHNESSMETALLICMAPCHANNEL=(property.PBR_MATERIAL&&property.OCCLUSIONROUGHNESSMETALLICMAP&&material._cf.occlusionRoughnessMetallicTexture.node._vf.channel===1)?1:0;property.SPECULARGLOSSINESSMAPCHANNEL=(property.PBR_MATERIAL&&property.SPECULARGLOSSINESSMAP&&material._cf.specularGlossinessTexture.node._vf.channel===1)?1:0;property.ALPHAMASK=(property.PBR_MATERIAL&&material._vf.alphaMode=="MASK")?1:0;property.UNLIT=(property.PBR_MATERIAL&&material._vf.unlit)?1:0;property.GAMMACORRECTION=environment._vf.gammaCorrectionDefault;property.KHR_MATERIAL_COMMONS=0;} property.toIdentifier=function(){delete this.id;var id="";for(var p in this){if(this[p]!=this.toIdentifier&&this[p]!=this.toString){id+=this[p];}} this.id=id;return id;};property.toString=function(){var str="";for(var p in this){if(this[p]!=this.toIdentifier&&this[p]!=this.toString){str+=p+": "+this[p]+", ";}} return str;};property.toIdentifier();return property;};x3dom.Utils.lerp=function(value1,value2,amount) {amount=amount<0?0:amount;amount=amount>1?1:amount;return value1+(value2-value1)*amount;} x3dom.Utils.wrapProgram=function(gl,program,shaderID) {var shader={shaderID:shaderID,program:program};shader.bind=function(){gl.useProgram(program);};var loc=null;var obj=null;var i,glErr;var numUniforms=gl.getProgramParameter(program,gl.ACTIVE_UNIFORMS);for(i=0;i>4) {case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:out+=String.fromCharCode(c);break;case 12:case 13:char2=array[i++];out+=String.fromCharCode(((c&0x1F)<<6)|(char2&0x3F));break;case 14:char2=array[i++];char3=array[i++];out+=String.fromCharCode(((c&0x0F)<<12)|((char2&0x3F)<<6)|((char3&0x3F)<<0));break;}} return JSON.parse(out);} x3dom.Utils.arrayBufferToObjectURL=function(buffer,mimetype) {return URL.createObjectURL(new Blob([new Uint8Array(buffer)],{type:mimetype}));} x3dom.Utils.dataURIToObjectURL=function(dataURI) {if(dataURI.indexOf("data:")==-1) {return dataURI;} var parts=dataURI.split(",");var mimetype=parts[0].split(':')[1].split(';')[0];var data=parts[1];var binaryString=window.atob(data);var byteLength=binaryString.length;var bytes=new Uint8Array(byteLength);for(var i=0;izFar) {return;} zNear=(zNear>1)?1:zNear;zFar=(zFar>1)?1:zFar;if(this.states['depthRange'].zNear!=zNear||this.states['depthRange'].zFar!=zFar) {this.gl.depthRange(zNear,zFar);this.states['depthRange'].zNear=zNear;this.states['depthRange'].zFar=zFar;}};x3dom.StateManager.prototype.viewport=function(x,y,width,height) {if(this.states['viewport'].x!=x||this.states['viewport'].y!=y||this.states['viewport'].width!=width||this.states['viewport'].height!=height) {this.gl.viewport(x,y,width,height);this.states['viewport'].x=x;this.states['viewport'].y=y;this.states['viewport'].width=width;this.states['viewport'].height=height;}};x3dom.StateManager.prototype.bindFramebuffer=function(target,framebuffer) {this.gl.bindFramebuffer(target,framebuffer);this.initStates();};x3dom.BinaryContainerLoader={outOfMemory:false,checkError:function(gl){var glErr=gl.getError();if(glErr){if(glErr==gl.OUT_OF_MEMORY){this.outOfMemory=true;x3dom.debug.logError("GL-Error "+glErr+" on loading binary container (out of memory).");console.error("WebGL: OUT_OF_MEMORY");} else{x3dom.debug.logError("GL-Error "+glErr+" on loading binary container.");}}}};x3dom.BinaryContainerLoader.setupBinGeo=function(shape,sp,gl,viewarea,currContext) {if(this.outOfMemory){return;} var t00=new Date().getTime();var that=this;var binGeo=shape._cf.geometry.node;shape._webgl.binaryGeometry=-1;shape._webgl.internalDownloadCount=((binGeo._vf.index.length>0)?1:0)+ ((binGeo._hasStrideOffset&&binGeo._vf.coord.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.coord.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.normal.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.texCoord.length>0)?1:0)+ ((!binGeo._hasStrideOffset&&binGeo._vf.color.length>0)?1:0);var createTriangleSoup=(binGeo._vf.normalPerVertex==false)||((binGeo._vf.index.length>0)&&(binGeo._vf.indexType=="Int32"||(binGeo._vf.indexType=="Uint32"&&!x3dom.caps.INDEX_UINT)));shape._webgl.makeSeparateTris={index:null,coord:null,normal:null,texCoord:null,color:null,pushBuffer:function(name,buf){this[name]=buf;if(--shape._webgl.internalDownloadCount==0){if(this.coord) this.createMesh();shape._nameSpace.doc.needRender=true;} if(--shape._nameSpace.doc.downloadCount==0) shape._nameSpace.doc.needRender=true;},createMesh:function(){var geoNode=binGeo;if(geoNode._hasStrideOffset){x3dom.debug.logError(geoNode._vf.indexType+" index type and per-face normals not supported for interleaved arrays.");return;} for(var k=0;k3)posBuf.push(this.coord[j+3]);if(this.color){colBuf.push(this.color[j]);colBuf.push(this.color[j+1]);colBuf.push(this.color[j+2]);if(dataLen>3)colBuf.push(this.color[j+3]);} if(this.texCoord){l=texDataLen*(this.index?this.index[i]:i);texcBuf.push(this.texCoord[l]);texcBuf.push(this.texCoord[l+1]);if(texDataLen>3){texcBuf.push(this.texCoord[l+2]);texcBuf.push(this.texCoord[l+3]);}} j=dataLen*(this.index?this.index[i+1]:i+1);var p1=new x3dom.fields.SFVec3f(bgSize.x*this.coord[j]/bgPrecisionMax,bgSize.y*this.coord[j+1]/bgPrecisionMax,bgSize.z*this.coord[j+2]/bgPrecisionMax);posBuf.push(this.coord[j]);posBuf.push(this.coord[j+1]);posBuf.push(this.coord[j+2]);if(dataLen>3)posBuf.push(this.coord[j+3]);if(this.color){colBuf.push(this.color[j]);colBuf.push(this.color[j+1]);colBuf.push(this.color[j+2]);if(dataLen>3)colBuf.push(this.color[j+3]);} if(this.texCoord){l=texDataLen*(this.index?this.index[i+1]:i+1);texcBuf.push(this.texCoord[l]);texcBuf.push(this.texCoord[l+1]);if(texDataLen>3){texcBuf.push(this.texCoord[l+2]);texcBuf.push(this.texCoord[l+3]);}} j=dataLen*(this.index?this.index[i+2]:i+2);var p2=new x3dom.fields.SFVec3f(bgSize.x*this.coord[j]/bgPrecisionMax,bgSize.y*this.coord[j+1]/bgPrecisionMax,bgSize.z*this.coord[j+2]/bgPrecisionMax);posBuf.push(this.coord[j]);posBuf.push(this.coord[j+1]);posBuf.push(this.coord[j+2]);if(dataLen>3)posBuf.push(this.coord[j+3]);if(this.color){colBuf.push(this.color[j]);colBuf.push(this.color[j+1]);colBuf.push(this.color[j+2]);if(dataLen>3)colBuf.push(this.color[j+3]);} if(this.texCoord){l=texDataLen*(this.index?this.index[i+2]:i+2);texcBuf.push(this.texCoord[l]);texcBuf.push(this.texCoord[l+1]);if(texDataLen>3){texcBuf.push(this.texCoord[l+2]);texcBuf.push(this.texCoord[l+3]);}} var a=p0.subtract(p1);var b=p1.subtract(p2);var norm=a.cross(b).normalize();for(j=0;j<3;j++){normBuf.push(norm.x);normBuf.push(norm.y);normBuf.push(norm.z);}} var buffer=gl.createBuffer();shape._webgl.buffers[x3dom.BUFFER_IDX.POSITION]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,x3dom.Utils.getArrayBufferView(geoNode._vf.coordType,posBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.position,geoNode._mesh._numPosComponents,shape._webgl.coordType,false,shape._coordStrideOffset[0],shape._coordStrideOffset[1]);gl.enableVertexAttribArray(sp.position);buffer=gl.createBuffer();shape._webgl.buffers[x3dom.BUFFER_IDX.NORMAL]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(normBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);gl.enableVertexAttribArray(sp.normal);if(this.texCoord) {buffer=gl.createBuffer();shape._webgl.buffers[x3dom.BUFFER_IDX.TEXCOORD]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,x3dom.Utils.getArrayBufferView(geoNode._vf.texCoordType,texcBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.texcoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);gl.enableVertexAttribArray(sp.texcoord);} if(this.color) {buffer=gl.createBuffer();shape._webgl.buffers[x3dom.BUFFER_IDX.COLOR]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,x3dom.Utils.getArrayBufferView(geoNode._vf.colorType,colBuf),gl.STATIC_DRAW);gl.vertexAttribPointer(sp.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);gl.enableVertexAttribArray(sp.color);} geoNode._vf.vertexCount=[];geoNode._vf.vertexCount[0]=posBuf.length/dataLen;geoNode._mesh._numCoords=geoNode._vf.vertexCount[0];geoNode._mesh._numFaces=geoNode._vf.vertexCount[0]/3;shape._webgl.primType=[];shape._webgl.primType[0]=gl.TRIANGLES;posBuf=null;normBuf=null;texcBuf=null;colBuf=null;this.index=null;this.coord=null;this.normal=null;this.texCoord=null;this.color=null;that.checkError(gl);delete shape._webgl.shader;shape._webgl.shader=currContext.cache.getDynamicShader(gl,viewarea,shape);}};if(binGeo._vf.index.length>0) {shape._webgl.binaryGeometry=1;var xmlhttp0=new XMLHttpRequest();xmlhttp0.open("GET",shape._nameSpace.getURL(binGeo._vf.index),true);xmlhttp0.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp0);xmlhttp0.onload=function() {shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp0.status!=200){x3dom.debug.logError("XHR1/ index load failed with status: "+xmlhttp0.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp0.response):xmlhttp0.response;var geoNode=binGeo;var attribTypeStr=geoNode._vf.indexType;var indexArray=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("index",indexArray);return;} var indicesBuffer=gl.createBuffer();if(x3dom.caps.INDEX_UINT&&attribTypeStr=="Uint32"){shape._webgl.indexType=gl.UNSIGNED_INT;} else{shape._webgl.indexType=gl.UNSIGNED_SHORT;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indicesBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.STATIC_DRAW);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,null);if(geoNode._vf.vertexCount[0]==0) geoNode._vf.vertexCount[0]=indexArray.length;geoNode._mesh._numFaces=0;for(var i=0;i0) {var xmlhttp=new XMLHttpRequest();xmlhttp.open("GET",shape._nameSpace.getURL(binGeo._vf.coord),true);xmlhttp.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp);xmlhttp.onload=function() {shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp.status!=200){x3dom.debug.logError("XHR1/ interleaved array load failed with status: "+xmlhttp.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp.response):xmlhttp.response;var geoNode=binGeo;var attribTypeStr=geoNode._vf.coordType;shape._webgl.coordType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);shape._webgl.normalType=shape._webgl.coordType;shape._webgl.texCoordType=shape._webgl.coordType;shape._webgl.colorType=shape._webgl.coordType;var attributes=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);var dataLen=shape._coordStrideOffset[0]/x3dom.Utils.getDataTypeSize(attribTypeStr);if(dataLen) geoNode._mesh._numCoords=attributes.length/dataLen;if(geoNode._vf.index.length==0){for(var i=0;i0) {shape._webgl.buffers[x3dom.BUFFER_IDX.NORMAL]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,attributes,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);gl.enableVertexAttribArray(sp.normal);} if(geoNode._vf.texCoord.length>0) {shape._webgl.buffers[x3dom.BUFFER_IDX.TEXCOORD]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,attributes,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.texcoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);gl.enableVertexAttribArray(sp.texcoord);} if(geoNode._vf.color.length>0) {shape._webgl.buffers[x3dom.BUFFER_IDX.COLOR]=buffer;gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,attributes,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);gl.enableVertexAttribArray(sp.color);} attributes=null;if(shape._webgl.internalDownloadCount==0) {shape._nameSpace.doc.needRender=true;} that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR/ interleaved array load time: "+t11+" ms");shape._webgl.buffers[x3dom.BUFFER_IDX.POSITION]=buffer;};} if(!binGeo._hasStrideOffset&&binGeo._vf.coord.length>0) {var xmlhttp1=new XMLHttpRequest();xmlhttp1.open("GET",shape._nameSpace.getURL(binGeo._vf.coord),true);xmlhttp1.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp1);xmlhttp1.onload=function() {shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp1.status!=200){x3dom.debug.logError("XHR1/ coord load failed with status: "+xmlhttp1.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp1.response):xmlhttp1.response;var geoNode=binGeo;var i=0;var attribTypeStr=geoNode._vf.coordType;shape._webgl.coordType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var vertices=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("coord",vertices);return;} gl.bindAttribLocation(sp.program,0,"position");var positionBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,null);geoNode._mesh._numCoords=vertices.length/geoNode._mesh._numPosComponents;if(geoNode._vf.index.length==0){for(i=0;ivertices[i+0]){min.x=vertices[i+0];} if(min.y>vertices[i+1]){min.y=vertices[i+1];} if(min.z>vertices[i+2]){min.z=vertices[i+2];} if(max.x0) {var xmlhttp2=new XMLHttpRequest();xmlhttp2.open("GET",shape._nameSpace.getURL(binGeo._vf.normal),true);xmlhttp2.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp2);xmlhttp2.onload=function() {shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp2.status!=200){x3dom.debug.logError("XHR2/ normal load failed with status: "+xmlhttp2.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp2.response):xmlhttp2.response;var attribTypeStr=binGeo._vf.normalType;shape._webgl.normalType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var normals=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("normal",normals);return;} var normalBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,normalBuffer);gl.bufferData(gl.ARRAY_BUFFER,normals,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,null);normals=null;if(shape._webgl.internalDownloadCount==0) {shape._nameSpace.doc.needRender=true;} that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR2/ normal load time: "+t11+" ms");shape._webgl.buffers[x3dom.BUFFER_IDX.NORMAL]=normalBuffer;};} if(!binGeo._hasStrideOffset&&binGeo._vf.texCoord.length>0) {var xmlhttp3=new XMLHttpRequest();xmlhttp3.open("GET",shape._nameSpace.getURL(binGeo._vf.texCoord),true);xmlhttp3.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp3);xmlhttp3.onload=function() {var i,j;var tmp;shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp3.status!=200){x3dom.debug.logError("XHR3/ texcoord load failed with status: "+xmlhttp3.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp3.response):xmlhttp3.response;var attribTypeStr=binGeo._vf.texCoordType;shape._webgl.texCoordType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var texCoords=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("texCoord",texCoords);return;} if(binGeo._vf["idsPerVertex"]) {var idBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,idBuffer);var ids=x3dom.Utils.getArrayBufferView("Float32",texCoords.length/2);for(i=0,j=0;i0) {var xmlhttp4=new XMLHttpRequest();xmlhttp4.open("GET",shape._nameSpace.getURL(binGeo._vf.color),true);xmlhttp4.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp4);xmlhttp4.onload=function() {shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp4.status!=200){x3dom.debug.logError("XHR4/ color load failed with status: "+xmlhttp4.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp4.response):xmlhttp4.response;var attribTypeStr=binGeo._vf.colorType;shape._webgl.colorType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var colors=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("color",colors);return;} var colorBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,null);colors=null;if(shape._webgl.internalDownloadCount==0) {shape._nameSpace.doc.needRender=true;} that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR4/ color load time: "+t11+" ms");shape._webgl.buffers[x3dom.BUFFER_IDX.COLOR]=colorBuffer;};} if(!binGeo._hasStrideOffset&&binGeo._vf.tangent.length>0) {var xmlhttp5=new XMLHttpRequest();xmlhttp5.open("GET",shape._nameSpace.getURL(binGeo._vf.normal),true);xmlhttp5.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp5);xmlhttp5.onload=function() {shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp5.status!=200){x3dom.debug.logError("XHR2/ normal load failed with status: "+xmlhttp5.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp5.response):xmlhttp5.response;var attribTypeStr=binGeo._vf.tangentType;shape._webgl.tangentType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var tangents=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("tangent",tangents);return;} var tangentBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,tangentBuffer);gl.bufferData(gl.ARRAY_BUFFER,tangents,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,null);tangents=null;if(shape._webgl.internalDownloadCount==0) {shape._nameSpace.doc.needRender=true;} that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR5/ normal load time: "+t11+" ms");shape._webgl.buffers[x3dom.BUFFER_IDX.TANGENT]=tangentBuffer;};} if(!binGeo._hasStrideOffset&&binGeo._vf.binormal.length>0) {var xmlhttp6=new XMLHttpRequest();xmlhttp6.open("GET",shape._nameSpace.getURL(binGeo._vf.normal),true);xmlhttp6.responseType="arraybuffer";shape._nameSpace.doc.incrementDownloads();x3dom.RequestManager.addRequest(xmlhttp6);xmlhttp6.onload=function() {shape._nameSpace.doc.decrementDownloads();shape._webgl.internalDownloadCount-=1;if(xmlhttp6.status!=200){x3dom.debug.logError("XHR6/ normal load failed with status: "+xmlhttp6.status);return;} if(!shape._webgl) return;var XHR_buffer=binGeo._vf.compressed==true?x3dom.Utils.gunzip(xmlhttp6.response):xmlhttp6.response;var attribTypeStr=binGeo._vf.binormalType;shape._webgl.binormalType=x3dom.Utils.getVertexAttribType(attribTypeStr,gl);var binormals=x3dom.Utils.getArrayBufferView(attribTypeStr,XHR_buffer);if(createTriangleSoup){shape._webgl.makeSeparateTris.pushBuffer("binormal",binormals);return;} var binormalBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,binormalBuffer);gl.bufferData(gl.ARRAY_BUFFER,binormals,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,null);binormals=null;if(shape._webgl.internalDownloadCount==0) {shape._nameSpace.doc.needRender=true;} that.checkError(gl);var t11=new Date().getTime()-t00;x3dom.debug.logInfo("XHR6/ normal load time: "+t11+" ms");shape._webgl.buffers[x3dom.BUFFER_IDX.BITANGENT]=binormalBuffer;};}};x3dom.BinaryContainerLoader.setupPopGeo=function(shape,sp,gl,viewarea,currContext) {if(this.outOfMemory){return;} var popGeo=shape._cf.geometry.node;if(popGeo.hasIndex()){shape._webgl.popGeometry=1;shape._webgl.buffers[x3dom.BUFFER_IDX.INDEX]=gl.createBuffer();gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,shape._webgl.buffers[x3dom.BUFFER_IDX.INDEX]);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,popGeo.getTotalNumberOfIndices()*2,gl.STATIC_DRAW);shape._webgl.buffers[x3dom.BUFFER_IDX.ID]=gl.createBuffer();var idBuffer=new Float32Array(popGeo._vf.vertexBufferSize);(function(){for(var i=0;i0){redrawNeeded=true;var indexDataView=new Uint8Array(data,0,indexDataLengthInBytes);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,shape._webgl.buffers[x3dom.BUFFER_IDX.INDEX]);(function(){var indexDataOffset=0;for(var i=0;i0){redrawNeeded=true;var attributeDataView=new Uint8Array(data,indexDataLengthInBytes,vertexDataLengthInBytes);gl.bindBuffer(gl.ARRAY_BUFFER,shape._webgl.buffers[x3dom.BUFFER_IDX.POSITION]);if(!popGeo.hasIndex()){gl.bufferSubData(gl.ARRAY_BUFFER,shape._webgl.currentNumVertices*popGeo.getAttributeStride(),attributeDataView);} else{gl.bufferSubData(gl.ARRAY_BUFFER,popGeo.getVertexDataBufferOffset(lvl)*popGeo.getAttributeStride(),attributeDataView);} shape._webgl.numVerticesAtLevel[lvl]=vertexDataLengthInBytes/popGeo.getAttributeStride();shape._webgl.currentNumVertices+=shape._webgl.numVerticesAtLevel[lvl];} (function(){var numValidIndices=0;for(var i=shape._webgl.levelsAvailable;i0&&env._lowPriorityThreshold<1);this.sortTrans=drawableCollectionConfig.sortTrans;this.prioLevels=10;this.maxTreshold=100;this.sortBySortKey=false;this.sortByPriority=false;this.numberOfNodes=0;this.length=0;};x3dom.DrawableCollection.prototype.cull=function(transform,graphState,singlePath,planeMask){var node=graphState.boundedNode;if(!node||!node._vf.render){return-1;} var volume=node.getVolume();var MASK_SET=63;if(this.frustumCulling&&graphState.needCulling){var wvol;if(singlePath&&!graphState.worldVolume.isValid()){graphState.worldVolume.transformFrom(transform,volume);wvol=graphState.worldVolume;} else if(planeMask0||node.forceUpdateCoverage()){var modelViewMat=this.viewMatrix.mult(transform);graphState.center=modelViewMat.multMatrixPnt(volume.getCenter());var rVec=modelViewMat.multMatrixVec(volume.getRadialVec());var r=rVec.length();var dist=Math.max(-graphState.center.z-r,this.near);var projPixelLength=dist*this.pixelHeightAtDistOne;graphState.coverage=(r*2.0)/projPixelLength;if(this.smallFeatureThreshold>0&&graphState.coverage0){drawable.zPos=graphState.center.z;} else{var center=transform.multMatrixPnt(shape.getCenter());center=this.viewMatrix.multMatrixPnt(center);drawable.zPos=center.z;}} if(!this.sortBySortKey&&drawable.sortKey!=0){this.sortBySortKey=true;} if(this.collection[drawable.sortType]===undefined){this.collection[drawable.sortType]=[];} this.collection[drawable.sortType].push(drawable);this.length++;if(this.context&&this.gl){this.context.setupShape(this.gl,drawable,this.viewarea);}};x3dom.DrawableCollection.prototype.addDrawable=function(drawable){drawable.shaderID=drawable.shape.getShaderProperties(this.viewarea).id;var appearance=drawable.shape._cf.appearance.node;drawable.sortType=appearance?appearance._vf.sortType.toLowerCase():"opaque";drawable.sortKey=appearance?appearance._vf.sortKey:0;if(drawable.sortType=='transparent'){var center=drawable.transform.multMatrixPnt(drawable.shape.getCenter());center=this.viewMatrix.multMatrixPnt(center);drawable.zPos=center.z;} if(!this.sortBySortKey&&drawable.sortKey!=0){this.sortBySortKey=true;} if(this.collection[drawable.sortType]===undefined){this.collection[drawable.sortType]=[];} this.collection[drawable.sortType].push(drawable);this.length++;if(this.context&&this.gl){this.context.setupShape(this.gl,drawable,this.viewarea);}};x3dom.DrawableCollection.prototype.calculatePriority=function(graphState){var priority=Math.max(0,graphState.coverage);var pl=this.prioLevels-1;priority=Math.min(Math.round(priority/(this.maxTreshold/pl)),pl);return priority;};x3dom.DrawableCollection.prototype.concat=function(){var opaque=(this.collection['opaque']!==undefined)?this.collection['opaque']:[];var transparent=(this.collection['transparent']!==undefined)?this.collection['transparent']:[];this.collection=opaque.concat(transparent);};x3dom.DrawableCollection.prototype.get=function(idx){return this.collection[idx];};x3dom.DrawableCollection.prototype.sort=function(){var opaque=[];var transparent=[];var that=this;if(this.collection['opaque']!==undefined){if(this.sortOpaque){this.collection['opaque'].sort(function(a,b){if(a.sortKey==b.sortKey||!that.sortBySortKey){return b.priority-a.priority;} return a.sortKey-b.sortKey;});} opaque=this.collection['opaque'];} if(this.collection['transparent']!==undefined){if(this.sortTrans){this.collection['transparent'].sort(function(a,b){if(a.sortKey==b.sortKey||!that.sortBySortKey){if(a.priority==b.priority||!that.sortByPriority){return a.zPos-b.zPos;} return b.priority-a.priority;} return a.sortKey-b.sortKey;});} transparent=this.collection['transparent'];} this.collection=opaque.concat(transparent);};x3dom.DrawableCollection.prototype.forEach=function(fnc,maxPriority){maxPriority=(maxPriority!==undefined)?Math.min(maxPriority,this.prioLevels):this.prioLevels;var sortKey,priority,shaderID,drawable;for(sortKey=0;sortKey0;--priority) {if(this.collection['opaque'][sortKey][priority]!==undefined) {for(shaderID in this.collection['opaque'][sortKey][priority]) {for(drawable=0;drawable0;--priority) {if(this.collection['transparent'][sortKey][priority]!==undefined) {for(var shaderId in this.collection['transparent'][sortKey][priority]) {this.collection['transparent'][sortKey][priority][shaderId].sort(function(a,b){return a.zPos-b.zPos});for(drawable=0;drawable0&&that._buttonState!=4){var x=that._gridSize*Math.round(track.x/that._gridSize);var y=that._gridSize*Math.round(track.y/that._gridSize);var z=that._gridSize*Math.round(track.z/that._gridSize);track=new x3dom.fields.SFVec3f(x,y,z);} if(!that._matrixTrafo){if(that._buttonState==4){that._moveable.setAttribute("rotation",track.toAxisAngle().toString());} else{that._moveable.setAttribute("translation",track.toString());}} else{if(that._buttonState==4){that._matrixTrafo.setRotate(track);} else{that._matrixTrafo.setTranslate(track);} that._moveable.setAttribute("matrix",that._matrixTrafo.toGL().toString());} if(that._callback){that._callback(that._moveable,track);}} that._lastX=pos[0];that._lastY=pos[1];}}};x3dom.Moveable.prototype.stop=function(event){for(var i=0,n=this._iMove.length;i>>8&255]<<16|H[b>>>16&255]<<8|H[b>>>24&255])>>32-a:H[b]>>8-a);if(8>a+f)g=g<>a-k-1&1,8===++f&&(f=0,d[e++]=H[g],g=0,e===d.length&&(d=this.f()));d[e]=g;this.buffer=d;this.m=f;this.index=e};F.prototype.finish=function(){var b=this.buffer,a=this.index,c;0ca;++ca){for(var K=ca,da=K,ea=7,K=K>>>1;K;K>>>=1)da<<=1,da|=K&1,--ea;ba[ca]=(da<>>0}var H=ba;function ja(b,a,c){var d,e="number"===typeof a?a:a=0,f="number"===typeof c?c:b.length;d=-1;for(e=f&7;e--;++a)d=d>>>8^O[(d^b[a])&255];for(e=f>>3;e--;a+=8)d=d>>>8^O[(d^b[a])&255],d=d>>>8^O[(d^b[a+1])&255],d=d>>>8^O[(d^b[a+2])&255],d=d>>>8^O[(d^b[a+3])&255],d=d>>>8^O[(d^b[a+4])&255],d=d>>>8^O[(d^b[a+5])&255],d=d>>>8^O[(d^b[a+6])&255],d=d>>>8^O[(d^b[a+7])&255];return(d^4294967295)>>>0} var ka=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918E3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],O=B?new Uint32Array(ka):ka;function P(){}P.prototype.getName=function(){return this.name};P.prototype.getData=function(){return this.data};P.prototype.Y=function(){return this.Z};A("Zlib.GunzipMember",P);A("Zlib.GunzipMember.prototype.getName",P.prototype.getName);A("Zlib.GunzipMember.prototype.getData",P.prototype.getData);A("Zlib.GunzipMember.prototype.getMtime",P.prototype.Y);function la(b){this.buffer=new(B?Uint16Array:Array)(2*b);this.length=0}la.prototype.getParent=function(b){return 2*((b-2)/4|0)};la.prototype.push=function(b,a){var c,d,e=this.buffer,f;c=this.length;e[this.length++]=a;for(e[this.length++]=b;0e[d])f=e[c],e[c]=e[d],e[d]=f,f=e[c+1],e[c+1]=e[d+1],e[d+1]=f,c=d;else break;return this.length};la.prototype.pop=function(){var b,a,c=this.buffer,d,e,f;a=c[0];b=c[1];this.length-=2;c[0]=c[this.length];c[1]=c[this.length+1];for(f=0;;){e=2*f+2;if(e>=this.length)break;e+2c[e]&&(e+=2);if(c[e]>c[f])d=c[f],c[f]=c[e],c[e]=d,d=c[f+1],c[f+1]=c[e+1],c[e+1]=d;else break;f=e}return{index:b,value:a,length:this.length}};function ma(b){var a=b.length,c=0,d=Number.POSITIVE_INFINITY,e,f,g,k,h,l,s,p,m,n;for(p=0;pc&&(c=b[p]),b[p]>=1;n=g<<16|p;for(m=l;mS;S++)switch(u){case 143>=S:sa.push([S+48,8]);break;case 255>=S:sa.push([S-144+400,9]);break;case 279>=S:sa.push([S-256+0,7]);break;case 287>=S:sa.push([S-280+192,8]);break;default:q("invalid literal: "+S)} na.prototype.g=function(){var b,a,c,d,e=this.input;switch(this.k){case 0:c=0;for(d=e.length;c>>8&255;m[n++]=l&255;m[n++]=l>>>8&255;if(B)m.set(f,n),n+=f.length,m=m.subarray(0,n);else{s=0;for(p=f.length;sz)for(;0z?z:138,D>z-3&&D=D?(I[G++]=17,I[G++]=D-3,M[17]++):(I[G++]=18,I[G++]=D-11,M[18]++),z-=D;else if(I[G++]=J[w],M[J[w]]++,z--,3>z)for(;0z?z:6,D>z-3&&DC;C++)wa[C]=oa[pb[C]];for(Z=19;4=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272,a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:q("invalid length: "+a)}}var a=[],c,d;for(c=3;258>=c;c++)d=b(c),a[c]=d[2]<<24|d[1]<<16|d[0];return a}(),Aa=B?new Uint32Array(ya):ya;function ta(b,a){function c(a,c){var b=a.Q,d=[],e=0,f;f=Aa[a.length];d[e++]=f&65535;d[e++]=f>>16&255;d[e++]=f>>24;var g;switch(u){case 1===b:g=[0,b-1,0];break;case 2===b:g=[1,b-2,0];break;case 3===b:g=[2,b-3,0];break;case 4===b:g=[3,b-4,0];break;case 6>=b:g=[4,b-5,1];break;case 8>=b:g=[5,b-7,1];break;case 12>=b:g=[6,b-9,2];break;case 16>=b:g=[7,b-13,2];break;case 24>=b:g=[8,b-17,3];break;case 32>=b:g=[9,b-25,3];break;case 48>=b:g=[10,b-33,4];break;case 64>=b:g=[11,b-49,4];break;case 96>=b:g=[12,b- 65,5];break;case 128>=b:g=[13,b-97,5];break;case 192>=b:g=[14,b-129,6];break;case 256>=b:g=[15,b-193,6];break;case 384>=b:g=[16,b-257,7];break;case 512>=b:g=[17,b-385,7];break;case 768>=b:g=[18,b-513,8];break;case 1024>=b:g=[19,b-769,8];break;case 1536>=b:g=[20,b-1025,9];break;case 2048>=b:g=[21,b-1537,9];break;case 3072>=b:g=[22,b-2049,10];break;case 4096>=b:g=[23,b-3073,10];break;case 6144>=b:g=[24,b-4097,11];break;case 8192>=b:g=[25,b-6145,11];break;case 12288>=b:g=[26,b-8193,12];break;case 16384>=b:g=[27,b-12289,12];break;case 24576>=b:g=[28,b-16385,13];break;case 32768>=b:g=[29,b-24577,13];break;default:q("invalid distance")}f=g;d[e++]=f[0];d[e++]=f[1];d[e++]=f[2];var h,k;h=0;for(k=d.length;h=f;)v[f++]=0;for(f=0;29>=f;)x[f++]=0}v[256]=1;d=0;for(e=a.length;d=e){p&&c(p,-1);f=0;for(g=e-d;fg&&a+gf&&(e=d,f=g);if(258===g)break}return new xa(f,a-e)} function ua(b,a){var c=b.length,d=new la(572),e=new(B?Uint8Array:Array)(c),f,g,k,h,l;if(!B)for(h=0;h2*e[n-1]+f[n]&&(e[n]=2*e[n-1]+f[n]),k[n]=Array(e[n]),h[n]=Array(e[n]);for(m=0;mb[m]?(k[n][r]=v,h[n][r]=a,x+=2):(k[n][r]=b[m],h[n][r]=m,++m);l[n]=0;1===f[n]&&d(n)}return g} function va(b){var a=new(B?Uint16Array:Array)(b.length),c=[],d=[],e=0,f,g,k,h;f=0;for(g=b.length;f>>=1}return a};function Da(b,a){this.input=b;this.b=this.c=0;this.i={};a&&(a.flags&&(this.i=a.flags),"string"===typeof a.filename&&(this.filename=a.filename),"string"===typeof a.comment&&(this.A=a.comment),a.deflateOptions&&(this.l=a.deflateOptions));this.l||(this.l={})} Da.prototype.g=function(){var b,a,c,d,e,f,g,k,h=new(B?Uint8Array:Array)(32768),l=0,s=this.input,p=this.c,m=this.filename,n=this.A;h[l++]=31;h[l++]=139;h[l++]=8;b=0;this.i.fname&&(b|=Ea);this.i.fcomment&&(b|=Fa);this.i.fhcrc&&(b|=Ga);h[l++]=b;a=(Date.now?Date.now():+new Date)/1E3|0;h[l++]=a&255;h[l++]=a>>>8&255;h[l++]=a>>>16&255;h[l++]=a>>>24&255;h[l++]=0;h[l++]=Ha;if(this.i.fname!==t){g=0;for(k=m.length;g>>8&255),h[l++]=f&255;h[l++]=0}if(this.i.comment){g=0;for(k=n.length;g>>8&255),h[l++]=f&255;h[l++]=0}this.i.fhcrc&&(c=ja(h,0,l)&65535,h[l++]=c&255,h[l++]=c>>>8&255);this.l.outputBuffer=h;this.l.outputIndex=l;e=new na(s,this.l);h=e.g();l=e.b;B&&(l+8>h.buffer.byteLength?(this.a=new Uint8Array(l+8),this.a.set(new Uint8Array(h.buffer)),h=this.a):h=new Uint8Array(h.buffer));d=ja(s,t,t);h[l++]=d&255;h[l++]=d>>>8&255;h[l++]=d>>>16&255;h[l++]=d>>>24&255;k=s.length;h[l++]=k&255;h[l++]=k>>>8&255;h[l++]=k>>>16&255;h[l++]=k>>>24&255;this.c=p;B&&l>>=1;switch(b){case 0:var a=this.input,c=this.c,d=this.a,e=this.b,f=a.length,g=t,k=t,h=d.length,l=t;this.e=this.j=0;c+1>=f&&q(Error("invalid uncompressed block header: LEN"));g=a[c++]|a[c++]<<8;c+1>=f&&q(Error("invalid uncompressed block header: NLEN"));k=a[c++]|a[c++]<<8;g===~k&&q(Error("invalid uncompressed block header: length verify"));c+g>a.length&&q(Error("input buffer is broken"));switch(this.r){case Ja:for(;e+g>d.length;){l=h-e;g-=l;if(B)d.set(a.subarray(c,c+l),e),e+=l,c+=l;else for(;l--;)d[e++]=a[c++];this.b=e;d=this.f();e=this.b}break;case Ia:for(;e+g>d.length;)d=this.f({F:2});break;default:q(Error("invalid inflate mode"))}if(B)d.set(a.subarray(c,c+g),e),e+=g,c+=g;else for(;g--;)d[e++]=a[c++];this.c=c;this.b=e;this.a=d;break;case 1:this.s(Za,$a);break;case 2:ab(this);break;default:q(Error("unknown BTYPE: "+b))}}return this.B()};var bb=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],cb=B?new Uint16Array(bb):bb,db=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],eb=B?new Uint16Array(db):db,fb=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],gb=B?new Uint8Array(fb):fb,hb=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ib=B?new Uint16Array(hb):hb,jb=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],kb=B?new Uint8Array(jb):jb,lb=new(B?Uint8Array:Array)(288),V,mb;V=0;for(mb=lb.length;V=V?8:255>=V?9:279>=V?7:8;var Za=ma(lb),nb=new(B?Uint8Array:Array)(30),ob,qb;ob=0;for(qb=nb.length;ob=g&&q(Error("input buffer is broken")),c|=e[f++]<>>a;b.e=d-a;b.c=f;return k} function rb(b,a){for(var c=b.j,d=b.e,e=b.input,f=b.c,g=e.length,k=a[0],h=a[1],l,s;d=g);)c|=e[f++]<>>16;b.j=c>>s;b.e=d-s;b.c=f;return l&65535} function ab(b){function a(a,b,c){var d,e=this.J,f,g;for(g=0;gf)d>=e&&(this.b=d,c=this.f(),d=this.b),c[d++]=f;else{g=f-257;h=eb[g];0=e&&(this.b=d,c=this.f(),d=this.b);for(;h--;)c[d]=c[d++-k]}for(;8<=this.e;)this.e-=8,this.c--;this.b=d};T.prototype.T=function(b,a){var c=this.a,d=this.b;this.C=b;for(var e=c.length,f,g,k,h;256!==(f=rb(this,b));)if(256>f)d>=e&&(c=this.f(),e=c.length),c[d++]=f;else{g=f-257;h=eb[g];0e&&(c=this.f(),e=c.length);for(;h--;)c[d]=c[d++-k]}for(;8<=this.e;)this.e-=8,this.c--;this.b=d};T.prototype.f=function(){var b=new(B?Uint8Array:Array)(this.b-32768),a=this.b-32768,c,d,e=this.a;if(B)b.set(e.subarray(32768,b.length));else{c=0;for(d=b.length;cc;++c)e[c]=e[a+c];this.b=32768;return e};T.prototype.U=function(b){var a,c=this.input.length/this.c+1|0,d,e,f,g=this.input,k=this.a;b&&("number"===typeof b.F&&(c=b.F),"number"===typeof b.P&&(c+=b.P));2>c?(d=(g.length-this.c)/this.C[2],f=258*(d/2)|0,e=fa&&(this.a.length=a),b=this.a);return this.buffer=b};function sb(b){this.input=b;this.c=0;this.t=[];this.D=!1}sb.prototype.X=function(){this.D||this.h();return this.t.slice()};sb.prototype.h=function(){for(var b=this.input.length;this.c>>0;ja(e,t,t)!==s&&q(Error("invalid CRC-32 checksum: 0x"+ja(e,t,t).toString(16)+" / 0x"+s.toString(16)));a.da=c=(p[m++]|p[m++]<<8|p[m++]<<16|p[m++]<<24)>>>0;(e.length&4294967295)!==c&&q(Error("invalid input size: "+(e.length&4294967295)+" / "+c));this.t.push(a);this.c=m}this.D=u;var n=this.t,r,v,x=0,Q=0,y;r=0;for(v=n.length;r>>0;b=a}for(var e=1,f=0,g=b.length,k,h=0;0>>0};function ub(b,a){var c,d;this.input=b;this.c=0;if(a||!(a={}))a.index&&(this.c=a.index),a.verify&&(this.$=a.verify);c=b[this.c++];d=b[this.c++];switch(c&15){case vb:this.method=vb;break;default:q(Error("unsupported compression method"))}0!==((c<<8)+d)%31&&q(Error("invalid fcheck flag:"+((c<<8)+d)%31));d&32&&q(Error("fdict flag is not supported"));this.L=new T(b,{index:this.c,bufferSize:a.bufferSize,bufferType:a.bufferType,resize:a.resize})} ub.prototype.h=function(){var b=this.input,a,c;a=this.L.h();this.c=this.L.c;this.$&&(c=(b[this.c++]<<24|b[this.c++]<<16|b[this.c++]<<8|b[this.c++])>>>0,c!==tb(a)&&q(Error("invalid adler-32 checksum")));return a};var vb=8;function wb(b,a){this.input=b;this.a=new(B?Uint8Array:Array)(32768);this.k=W.o;var c={},d;if((a||!(a={}))&&"number"===typeof a.compressionType)this.k=a.compressionType;for(d in a)c[d]=a[d];c.outputBuffer=this.a;this.K=new na(this.input,c)}var W=ra;wb.prototype.g=function(){var b,a,c,d,e,f,g,k=0;g=this.a;b=vb;switch(b){case vb:a=Math.LOG2E*Math.log(32768)-8;break;default:q(Error("invalid compression method"))}c=a<<4|b;g[k++]=c;switch(b){case vb:switch(this.k){case W.NONE:e=0;break;case W.v:e=1;break;case W.o:e=2;break;default:q(Error("unsupported compression type"))}break;default:q(Error("invalid compression method"))}d=e<<6|0;g[k++]=d|31-(256*c+d)%31;f=tb(this.input);this.K.b=k;g=this.K.g();k=g.length;B&&(g=new Uint8Array(g.buffer),g.length<=k+4&&(this.a=new Uint8Array(g.length+4),this.a.set(g),g=this.a),g=g.subarray(0,k+4));g[k++]=f>>24&255;g[k++]=f>>16&255;g[k++]=f>>8&255;g[k++]=f&255;return g};function xb(b,a){var c,d,e,f;if(Object.keys)c=Object.keys(a);else for(d in c=[],e=0,a)c[e++]=d;e=0;for(f=c.length;e0){this.scene=this.readScene(response,this.header);this.body=this.readBody(response,this.header);} this._mesh={};};x3dom.glTF.glTFLoader.prototype.getScene=function(shape,shaderProgram,gl,sceneName) {this.reset(shape,gl);if(sceneName==null) {sceneName=this.scene["scene"];} var scene=this.scene.scenes[sceneName];this.updateScene(shape,shaderProgram,gl,scene);};x3dom.glTF.glTFLoader.prototype.getMesh=function(shape,shaderProgram,gl,meshName) {this.reset(shape,gl);var mesh;if(meshName==null) {mesh=Object.keys(this.scene.meshes)[0];}else {for(var key in this.scene.meshes){if(this.scene.meshes.hasOwnProperty(key)&&key==meshName) {mesh=this.scene.meshes[key];break;}}} this.updateMesh(shape,shaderProgram,gl,mesh,new x3dom.fields.SFMatrix4f());};x3dom.glTF.glTFLoader.prototype.reset=function(shape,gl) {this._mesh._numCoords=0;this._mesh._numFaces=0;shape._webgl.externalGeometry=-1;if(this.loaded.bufferViews==null) this.loaded.bufferViews=this.loadBufferViews(shape,gl);};x3dom.glTF.glTFLoader.prototype.updateScene=function(shape,shaderProgram,gl,scene) {var nodes=scene["nodes"];for(var i=0;i0) for(var i=0;i_zratio){zfar=znear=-1;} viewpoint.setAttribute("DEF",id);viewpoint.setAttribute("fieldOfView",fov);viewpoint.setAttribute("zNear",znear);viewpoint.setAttribute("zFar",zfar);viewpoint.setAttribute("position","0 0 0");return viewpoint;};x3dom.glTF2Loader.prototype._generateX3DOrthoViewpoint=function(id,camera) {var viewpoint=document.createElement("orthoviewpoint");this._generateX3DMetadata(camera,viewpoint);var xmag=camera.xmag||1;var ymag=camera.ymag||1;var znear=camera.znear||-1;var zfar=camera.zfar||-1;var fov=[-xmag,-ymag,xmag,ymag];viewpoint.setAttribute("DEF",id);viewpoint.setAttribute("fieldOfView",fov);viewpoint.setAttribute("zNear",znear);viewpoint.setAttribute("zFar",zfar);viewpoint.setAttribute("position","0 0 0");return viewpoint;};x3dom.glTF2Loader.prototype._generateX3DShape=function(primitive) {var shape=document.createElement("shape");this._generateX3DMetadata(primitive,shape);var material=(primitive.material!=undefined)?this._gltf.materials[primitive.material]:{};shape.appendChild(this._generateX3DAppearance(material));shape.appendChild(this._generateX3DBufferGeometry(primitive));return shape;};x3dom.glTF2Loader.prototype._generateX3DAppearance=function(material) {var appearance=document.createElement("appearance");this._generateX3DMetadata(material,appearance);if(material.alphaMode==="BLEND") {appearance.setAttribute("sortType","transparent");} else {appearance.setAttribute("sortType","opaque");} appearance.appendChild(this._generateX3DPhysicalMaterial(material));if(this._textureTransform) {appearance.appendChild(this._textureTransform);this._textureTransform=undefined;} return appearance;};x3dom.glTF2Loader.prototype._generateX3DPhysicalMaterial=function(material) {var mat=document.createElement("physicalmaterial");if(this._USEorDEF(mat,"glTF_MATERIAL_"+material.name)) {return mat;} var texture;var baseColorFactor=[1,1,1,1];var emissiveFactor=material.emissiveFactor||[0,0,0];var metallicFactor=1;var roughnessFactor=1;var alphaMode=material.alphaMode||"OPAQUE";var alphaCutoff=material.alphaCutoff||0.5;var seperateOcclusion=true var model=undefined;var pbr=undefined;var channel=0;var transform;if(material.pbrMetallicRoughness) {pbr=material.pbrMetallicRoughness;model="roughnessMetallic";} else if(material.extensions&&material.extensions.KHR_materials_pbrSpecularGlossiness) {pbr=material.extensions.KHR_materials_pbrSpecularGlossiness;model="specularGlossiness";} if(model=="roughnessMetallic") {var baseColorFactor=pbr.baseColorFactor||[1,1,1,1];var metallicFactor=(pbr.metallicFactor!=undefined)?pbr.metallicFactor:1;var roughnessFactor=(pbr.roughnessFactor!=undefined)?pbr.roughnessFactor:1;if(pbr.baseColorTexture) {channel=(pbr.baseColorTexture.texCoord)?1:0;texture=this._gltf.textures[pbr.baseColorTexture.index];transform=(pbr.baseColorTexture.extensions&&pbr.baseColorTexture.extensions.KHR_texture_transform)?pbr.baseColorTexture.extensions.KHR_texture_transform:undefined;mat.appendChild(this._generateX3DImageTexture(texture,"baseColorTexture",channel,transform));} if(pbr.metallicRoughnessTexture) {channel=(pbr.metallicRoughnessTexture.texCoord)?1:0;texture=this._gltf.textures[pbr.metallicRoughnessTexture.index];transform=(pbr.metallicRoughnessTexture.extensions&&pbr.metallicRoughnessTexture.extensions.KHR_texture_transform)?pbr.metallicRoughnessTexture.extensions.KHR_texture_transform:undefined;if(material.occlusionTexture&&material.occlusionTexture.index==pbr.metallicRoughnessTexture.index) {seperateOcclusion=false;mat.appendChild(this._generateX3DImageTexture(texture,"occlusionRoughnessMetallicTexture",channel,transform));} else {mat.appendChild(this._generateX3DImageTexture(texture,"roughnessMetallicTexture",channel,transform));}} mat.setAttribute("baseColorFactor",baseColorFactor.join(" "));mat.setAttribute("metallicFactor",metallicFactor);mat.setAttribute("roughnessFactor",roughnessFactor);} else if(model=="specularGlossiness") {var diffuseFactor=pbr.diffuseFactor||[1,1,1,1];var specularFactor=pbr.specularFactor||[1,1,1];var glossinessFactor=(pbr.glossinessFactor!=undefined)?pbr.glossinessFactor:1;if(pbr.diffuseTexture) {channel=(pbr.diffuseTexture.texCoord)?1:0;texture=this._gltf.textures[pbr.diffuseTexture.index];transform=(pbr.diffuseTexture.extensions&&pbr.diffuseTexture.extensions.KHR_texture_transform)?pbr.diffuseTexture.extensions.KHR_texture_transform:undefined;mat.appendChild(this._generateX3DImageTexture(texture,"baseColorTexture",channel,transform));} if(pbr.specularGlossinessTexture) {channel=(pbr.specularGlossinessTexture.texCoord)?1:0;texture=this._gltf.textures[pbr.specularGlossinessTexture.index];transform=(pbr.specularGlossinessTexture.extensions&&pbr.specularGlossinessTexture.extensions.KHR_texture_transform)?pbr.specularGlossinessTexture.extensions.KHR_texture_transform:undefined;mat.appendChild(this._generateX3DImageTexture(texture,"specularGlossinessTexture",channel,transform));} mat.setAttribute("diffuseFactor",diffuseFactor.join(" "));mat.setAttribute("specularFactor",specularFactor.join(" "));mat.setAttribute("glossinessFactor",glossinessFactor);} if(material.normalTexture) {channel=(material.normalTexture.texCoord)?1:0;texture=this._gltf.textures[material.normalTexture.index];transform=(material.normalTexture.extensions&&material.normalTexture.extensions.KHR_texture_transform)?material.normalTexture.extensions.KHR_texture_transform:undefined;mat.appendChild(this._generateX3DImageTexture(texture,"normalTexture",channel,transform));} if(material.emissiveTexture) {channel=(material.emissiveTexture.texCoord)?1:0;texture=this._gltf.textures[material.emissiveTexture.index];transform=(material.emissiveTexture.extensions&&material.emissiveTexture.extensions.KHR_texture_transform)?material.emissiveTexture.extensions.KHR_texture_transform:undefined;mat.appendChild(this._generateX3DImageTexture(texture,"emissiveTexture",channel,transform));} if(material.occlusionTexture&&seperateOcclusion) {channel=(material.occlusionTexture.texCoord)?1:0;texture=this._gltf.textures[material.occlusionTexture.index];transform=(material.occlusionTexture.extensions&&material.occlusionTexture.extensions.KHR_texture_transform)?material.occlusionTexture.extensions.KHR_texture_transform:undefined;mat.appendChild(this._generateX3DImageTexture(texture,"occlusionTexture",channel,transform));} if(material.extensions&&material.extensions.KHR_materials_unlit) {mat.setAttribute("unlit",true);} mat.setAttribute("emissiveFactor",emissiveFactor.join(" "));mat.setAttribute("alphaMode",alphaMode);mat.setAttribute("alphaCutoff",alphaCutoff);mat.setAttribute("model",model);return mat;};x3dom.glTF2Loader.prototype._generateX3DImageTexture=function(texture,containerField,channel,transform) {var image=this._gltf.images[texture.source];var imagetexture=document.createElement("imagetexture");this._generateX3DMetadata(texture,imagetexture);imagetexture.setAttribute("origChannelCount","2");imagetexture.setAttribute("flipY","true");if(containerField) {imagetexture.setAttribute("containerField",containerField);} if(image.uri!=undefined) {imagetexture.setAttribute("url",x3dom.Utils.dataURIToObjectURL(image.uri));} if(texture.sampler!=undefined) {var sampler=this._gltf.samplers[texture.sampler];imagetexture.appendChild(this._createX3DTextureProperties(sampler));} if(channel) {imagetexture.setAttribute("channel","1");} if(transform) {this._textureTransform=this._createX3DTextureTransform(imagetexture,transform);} return imagetexture;};x3dom.glTF2Loader.prototype._createX3DTextureProperties=function(sampler) {var textureproperties=document.createElement("textureproperties");textureproperties.setAttribute("boundaryModeS",x3dom.Utils.boundaryModesDicX3D(sampler.wrapS));textureproperties.setAttribute("boundaryModeT",x3dom.Utils.boundaryModesDicX3D(sampler.wrapT));textureproperties.setAttribute("magnificationFilter",x3dom.Utils.magFilterDicX3D(sampler.magFilter));textureproperties.setAttribute("minificationFilter",x3dom.Utils.minFilterDicX3D(sampler.minFilter));if(sampler.minFilter==undefined||(sampler.minFilter>=9984&&sampler.minFilter<=9987)) {textureproperties.setAttribute("generateMipMaps","true");} return textureproperties;};x3dom.glTF2Loader.prototype._createX3DTextureTransform=function(imagetexture,transform) {var texturetransform=document.createElement("matrixtexturetransform");var offset=transform.offset||[0,0];var rotation=transform.rotation||0;var scale=transform.scale||[1,1];var negCenter=new x3dom.fields.SFVec3f(-0,-0,0);var posCenter=new x3dom.fields.SFVec3f(0,0,0);var trans3=new x3dom.fields.SFVec3f(offset[0],offset[1],0);var scale3=new x3dom.fields.SFVec3f(scale[0],scale[1],0);var trafo=x3dom.fields.SFMatrix4f.translation(posCenter.add(trans3)).mult(x3dom.fields.SFMatrix4f.rotationZ(rotation*-1.0)).mult(x3dom.fields.SFMatrix4f.scale(scale3)).mult(x3dom.fields.SFMatrix4f.translation(negCenter));texturetransform.setAttribute("matrix",trafo.toString());if(transform.texCoord) {imagetexture.setAttribute("channel",texCoord);} return texturetransform;};x3dom.glTF2Loader.prototype._generateX3DBufferGeometry=function(primitive) {var views=[];var bufferGeometry=document.createElement("buffergeometry");var centerAndSize=this._getCenterAndSize(primitive);bufferGeometry.setAttribute("buffer",this._bufferURI(primitive));bufferGeometry.setAttribute("position",centerAndSize.center.join(" "));bufferGeometry.setAttribute("size",centerAndSize.size.join(" "));bufferGeometry.setAttribute("vertexCount",this._getVertexCount(primitive));bufferGeometry.setAttribute("primType",this._primitiveType(primitive.mode));if(primitive.material!=undefined) {var material=this._gltf.materials[primitive.material];if(material.doubleSided) {bufferGeometry.setAttribute("solid","false");}} if(primitive.indices!=undefined) {var accessor=this._gltf.accessors[primitive.indices];var view=this._gltf.bufferViews[accessor.bufferView];view.id=accessor.bufferView;view.target=34963;var viewID=views.indexOf(view) if(view.target!=undefined&&viewID==-1) {viewID=views.push(view)-1;} bufferGeometry.appendChild(this._generateX3DBufferAccessor("INDEX",accessor,viewID));} for(var attribute in primitive.attributes) {var accessor=this._gltf.accessors[primitive.attributes[attribute]];var view=this._gltf.bufferViews[accessor.bufferView];view.target=34962;view.id=accessor.bufferView;var viewID=views.indexOf(view) if(view.target!=undefined&&viewID==-1) {viewID=views.push(view)-1;} bufferGeometry.appendChild(this._generateX3DBufferAccessor(attribute,accessor,viewID));} for(var i=0;ithis.primitiveType) polyMode=this.primitiveType;if(this.buffers[x3dom.BUFFER_IDX.INDEX]) gl.drawElements(polyMode,this.drawCount,this.buffers[x3dom.BUFFER_IDX.INDEX].type,this.buffers[x3dom.BUFFER_IDX.INDEX].offset);else gl.drawArrays(polyMode,0,this.drawCount);};x3dom.glTF.glTFTexture=function(gl,format,internalFormat,sampler,target,type,image,flip) {this.format=format;this.internalFormat=internalFormat;this.sampler=sampler;this.target=target;this.type=type;this.image=image;this.flip=flip;this.created=false;this.create(gl);};x3dom.glTF.glTFTexture.prototype.needsPowerOfTwo=function(gl) {var resize=true;resize&=(this.sampler.magFilter==gl.LINEAR||this.sampler.magFilter==gl.NEAREST);resize&=(this.sampler.minFilter==gl.LINEAR||this.sampler.minFilter==gl.NEAREST);resize&=(this.sampler.wrapS==gl.CLAMP_TO_EDGE);resize&=(this.sampler.wrapT==gl.CLAMP_TO_EDGE);return!resize;};x3dom.glTF.glTFTexture.prototype.needsMipMaps=function(gl) {var need=true;need&=(this.sampler.magFilter==gl.LINEAR||this.sampler.magFilter==gl.NEAREST);need&=(this.sampler.minFilter==gl.LINEAR||this.sampler.minFilter==gl.NEAREST);return!need;};x3dom.glTF.glTFTexture.prototype.create=function(gl) {if(this.image.complete==false) return;this.glTexture=gl.createTexture();var imgSrc=this.image;if(this.needsPowerOfTwo(gl)){var width=this.image.width;var height=this.image.height;var aspect=width/height;imgSrc=x3dom.Utils.scaleImage(this.image);var aspect2=imgSrc.width/imgSrc.height;if(Math.abs(aspect-aspect2)>0.01){console.warn("Image "+this.image.src+" was resized to power of two, but has unsupported aspect ratio and may be distorted!");}} if(this.flip) {gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);} gl.bindTexture(gl.TEXTURE_2D,this.glTexture);gl.texImage2D(gl.TEXTURE_2D,0,this.internalFormat,this.format,this.type,imgSrc);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,this.sampler.magFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,this.sampler.minFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,this.sampler.wrapS);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,this.sampler.wrapT);if(this.needsMipMaps(gl)) {gl.generateMipmap(gl.TEXTURE_2D);} if(this.flip) {gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,false);} gl.bindTexture(gl.TEXTURE_2D,null);this.created=true;};x3dom.glTF.glTFTexture.prototype.bind=function(gl,textureUnit,shaderProgram,uniformName) {gl.activeTexture(gl.TEXTURE0+textureUnit);if(!this.created) this.create(gl);gl.bindTexture(gl.TEXTURE_2D,this.glTexture);gl.uniform1i(gl.getUniformLocation(shaderProgram,uniformName),textureUnit);};x3dom.glTF.PBRMaterial=function() {this.baseColorFactor=[0.3,0.1,0.1,1];this.baseColorTex=null;this.metallicFactor=0;this.metallicTex=null;this.roughnessFactor=0.2;this.roughnessTex=null;this.normalTex=null;this.occlusionTex=null;this.doubleSided=false;this.technique=PBR_MATERIAL_TECHNIQUE.METALLICROUGHNESS;this.attributeMapping={};this.attributeMapping[x3dom.BUFFER_IDX.POSITION]="position";this.attributeMapping[x3dom.BUFFER_IDX.NORMAL]="normal";this.attributeMapping[x3dom.BUFFER_IDX.TEXCOORD]="texcoord";this.attributeMapping[x3dom.BUFFER_IDX.TANGENT]="tangent";this.attributeMapping[x3dom.BUFFER_IDX.BITANGENT]="bitangent";};x3dom.glTF.PBRMaterial.prototype.created=function() {if(this.baseColorTex!=null&&this.baseColorTex.created!=true) return false;if(this.metallicTex!=null&&this.metallicTex.created!=true) return false;if(this.roughnessTex!=null&&this.roughnessTex.created!=true) return false;if(this.normalTex!=null&&this.normalTex.created!=true) return false;if(this.occlusionTex!=null&&this.occlusionTex.created!=true) return false;return true;};x3dom.glTF.PBRMaterial.prototype.setShader=function(gl,cache,shape,properties) {properties.EMPTY_SHADER=0;properties.PBR_MATERIAL=1;if(this.baseColorTex!=null) properties.USE_BASECOLOR_TEX=1;else properties.USE_BASECOLOR_TEX=0;if(this.metallicTex!=null) properties.USE_METALLIC_TEX=1;else properties.USE_METALLIC_TEX=0;if(this.roughnessTex!=null) properties.USE_ROUGHNESS_TEX=1;else properties.USE_ROUGHNESS_TEX=0;if(this.normalTex!=null) properties.USE_NORMAL_TEX=1;else properties.USE_NORMAL_TEX=0;if(this.occlusionTex!=null) properties.USE_OCCLUSION_TEX=1;else properties.USE_OCCLUSION_TEX=0;properties.toIdentifier();this.program=cache.getShaderByProperties(gl,shape,properties);};x3dom.glTF.PBRMaterial.prototype.bind=function(gl,shaderProgram) {this.program.bind();for(var key in shaderProgram){if(!shaderProgram.hasOwnProperty(key)) continue;if(this.program.hasOwnProperty(key)) this.program[key]=shaderProgram[key];} if(this.baseColorTex!=null) this.baseColorTex.bind(gl,0,this.program.program,"baseColorTex");if(this.metallicTex!=null) this.metallicTex.bind(gl,1,this.program.program,"metallicTex");if(this.roughnessTex!=null) this.roughnessTex.bind(gl,2,this.program.program,"roughnessTex");if(this.normalTex!=null) this.normalTex.bind(gl,3,this.program.program,"normalTex");if(this.occlusionTex!=null) this.occlusionTex.bind(gl,4,this.program.program,"occlusionTex");this.program.baseColorFactor=this.baseColorFactor;this.program.metallicFactor=this.metallicFactor;this.program.roughnessFactor=this.roughnessFactor;this.program.technique=this.technique;};x3dom.glTF.glTFKHRMaterialCommons=function() {this.diffuse=[0.3,0.1,0.1,1];this.diffuseTex=null;this.emission=[0.0,0.0,0.0,1];this.emissionTex=null;this.specular=[0.8,0.8,0.8,1];this.specularTex=null;this.ambient=[0,0,0,1];this.shininess=2;this.transparency=0.0;this.globalAmbient=[0,0,0,1];this.lightVector=[1,0,0,1];this.doubleSided=false;this.technique=glTF_KHR_MATERIAL_COMMON_TECHNIQUE.PHONG;this.attributeMapping={};this.attributeMapping[x3dom.BUFFER_IDX.POSITION]="position";this.attributeMapping[x3dom.BUFFER_IDX.NORMAL]="normal";this.attributeMapping[x3dom.BUFFER_IDX.TEXCOORD]="texcoord";this.attributeMapping[x3dom.BUFFER_IDX.COLOR]="color";};x3dom.glTF.glTFKHRMaterialCommons.prototype.created=function() {if(this.diffuseTex!=null&&this.diffuseTex.created!=true) return false;if(this.emissionTex!=null&&this.emissionTex.created!=true) return false;if(this.specularTex!=null&&this.specularTex.created!=true) return false;return true;};x3dom.glTF.glTFKHRMaterialCommons.prototype.setShader=function(gl,cache,shape,properties) {properties.EMPTY_SHADER=0;properties.KHR_MATERIAL_COMMONS=1;if(this.diffuseTex!=null) properties.USE_DIFFUSE_TEX=1;else properties.USE_DIFFUSE_TEX=0;if(this.emissionTex!=null) properties.USE_SPECULAR_TEX=1;else properties.USE_SPECULAR_TEX=0;if(this.specularTex!=null) properties.USE_EMISSION_TEX=1;else properties.USE_EMISSION_TEX=0;properties.toIdentifier();this.program=cache.getShaderByProperties(gl,shape,properties);};x3dom.glTF.glTFKHRMaterialCommons.prototype.bind=function(gl,shaderProgram) {this.program.bind();for(var key in shaderProgram){if(!shaderProgram.hasOwnProperty(key)) continue;if(this.program.hasOwnProperty(key)) this.program[key]=this.updateTransforms(key,shaderProgram[key]);} if(this.diffuseTex!=null) this.diffuseTex.bind(gl,0,this.program.program,"diffuseTex");else this.program.diffuse=this.diffuse;if(this.emissionTex!=null) this.emissionTex.bind(gl,0,this.program.program,"emissionTex");else this.program.emission=this.emission;if(this.specularTex!=null) this.specularTex.bind(gl,0,this.program.program,"specularTex");else this.program.specular=this.specular;this.program.shininess=this.shininess;this.program.transparency=this.transparency;this.program.globalAmbient=this.globalAmbient;this.program.lightVector=this.lightVector;this.program.lightVector=this.lightVector;this.program.technique=this.technique;};x3dom.glTF.glTFKHRMaterialCommons.prototype.updateTransforms=function(uniform,value) {var matrix4f=new x3dom.fields.SFMatrix4f();function glMultMatrix4(gl,m){matrix4f.setFromArray(gl);return matrix4f.mult(m).toGL();};switch(uniform){case"modelViewInverseTransposeMatrix":var worldInverse=this.worldTransform.inverse();matrix4f.setFromArray(value);var mat=worldInverse.mult(matrix4f).transpose().toGL();var model_view_inv_gl=[mat[0],mat[1],mat[2],mat[4],mat[5],mat[6],mat[8],mat[9],mat[10]];return model_view_inv_gl;break;case"modelViewInverseMatrix":var worldInverse=this.worldTransform.inverse();matrix4f.setFromArray(value);return worldInverse.mult(matrix4f);break;case"modelViewMatrix":case"modelViewProjectionMatrix":case"modelMatrix":case"model":return glMultMatrix4(value,this.worldTransform);break;case"viewMatrix":case"projectionMatrix":return value;break;default:return value;break;} console.warn("switch default not encountered ?");return value;};x3dom.glTF.glTFMaterial=function(technique) {this.technique=technique;this.values={};this.semanticMapping={};this.attributeMapping={};this.textures={};for(var key in this.technique.uniforms) {if(this.technique.uniforms.hasOwnProperty(key)) {var parameter=this.technique.parameters[this.technique.uniforms[key]];if(parameter.semantic!=null) switch(parameter.semantic) {case"MODELVIEW":this.semanticMapping[key]="modelViewMatrix";break;case"MODELVIEWINVERSETRANSPOSE":this.semanticMapping[key]="modelViewInverseTransposeMatrix";break;case"PROJECTION":this.semanticMapping[key]="projectionMatrix";break;case"MODEL":this.semanticMapping[key]="modelMatrix";break;case"MODELVIEWPROJECTION":this.semanticMapping[key]="modelViewProjectionMatrix";break;case"VIEW":this.semanticMapping[key]="viewMatrix";break;case"MODELVIEWINVERSE":this.semanticMapping[key]="modelViewInverseMatrix";break;default:break;}}} for(var key in this.technique.attributes){if(this.technique.attributes.hasOwnProperty(key)){var parameter=this.technique.parameters[this.technique.attributes[key]];if(parameter.semantic!=null) switch(parameter.semantic){case"POSITION":this.attributeMapping[x3dom.BUFFER_IDX.POSITION]=key;break;case"NORMAL":this.attributeMapping[x3dom.BUFFER_IDX.NORMAL]=key;break;case"TEXCOORD_0":this.attributeMapping[x3dom.BUFFER_IDX.TEXCOORD]=key;break;case"COLOR":this.attributeMapping[x3dom.BUFFER_IDX.COLOR]=key;break;default:break;}}}};x3dom.glTF.glTFMaterial.prototype.created=function() {for(var key in this.textures){if(!this.textures.hasOwnProperty(key))continue;if(this.textures[key].created!=true) return false;} return true;};x3dom.glTF.glTFMaterial.prototype.bind=function(gl,shaderParameter) {if(this.program!=null) this.program.bind();this.updateTransforms(shaderParameter);var texUnit=0;for(var key in this.technique.uniforms) if(this.technique.uniforms.hasOwnProperty(key)) {var uniformName=this.technique.uniforms[key];if(this.textures[uniformName]!=null){var texture=this.textures[uniformName];texture.bind(gl,texUnit,this.program.program,key);texUnit++;} else if(this.values[uniformName]!=null) this.program[key]=this.values[uniformName];}};x3dom.glTF.glTFMaterial.prototype.updateTransforms=function(shaderParameter) {var matrix4f=new x3dom.fields.SFMatrix4f();function glMultMatrix4(gl,m){matrix4f.setFromArray(gl);return matrix4f.mult(m).toGL();} if(this.program!==null) {this.program.bind();for(var key in this.semanticMapping){if(!this.semanticMapping.hasOwnProperty(key))continue;var worldInverse;var mapping=this.semanticMapping[key];switch(mapping){case"modelViewMatrix":this.program[key]=shaderParameter.modelViewMatrix;break;case"viewMatrix":this.program[key]=shaderParameter.viewMatrix;break;case"modelViewInverseTransposeMatrix":worldInverse=this.worldTransform.inverse();matrix4f.setFromArray(shaderParameter.modelViewMatrixInverse);var mat=worldInverse.mult(matrix4f).transpose().toGL();var model_view_inv_gl=[mat[0],mat[1],mat[2],mat[4],mat[5],mat[6],mat[8],mat[9],mat[10]];this.program[key]=model_view_inv_gl;break;case"modelViewInverseMatrix":worldInverse=shaderParameter.model.inverse();matrix4f.setFromArray(shaderParameter.modelViewMatrixInverse);this.program[key]=worldInverse.mult(matrix4f);break;case"modelViewProjectionMatrix":this.program[key]=shaderParameter.modelViewProjectionMatrix;break;case"modelMatrix":this.program[key]=shaderParameter.model;break;case"projectionMatrix":this.program[key]=shaderParameter.projectionMatrix;break;default:break;}}}};x3dom.DDSLoader={};x3dom.DDSLoader.load=function(src) {return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest();xhr.open('GET',src,true);xhr.responseType="arraybuffer";xhr.onload=function() {var dds=x3dom.DDSLoader._read(xhr.response);if(dds) {resolve(dds);} else {reject(dds);}};xhr.onerror=function() {reject();};x3dom.RequestManager.addRequest(xhr);});} x3dom.DDSLoader._read=function(source) {if(source===undefined||source.byteLength<128) {return;} let dds={isCompressed:false,isVolume:false,isCubeMap:false,targets:[],data:[]};let int32Buffer=new Uint32Array(source,0,32);dds.header=x3dom.DDSLoader._readHeader(int32Buffer);int32Buffer=new Uint32Array(source,128,5);dds.header10=x3dom.DDSLoader._readHeader10(dds,int32Buffer);if(dds.header.dwMagic!=0x20534444) {return;} if(dds.header.dwSize!=0x7C) {return;} if(!x3dom.DDSLoader._readFormat(dds)) {return;} x3dom.DDSLoader._readMipmapCount(dds);x3dom.DDSLoader._readType(dds);this._readData(dds,source);return dds;} x3dom.DDSLoader._readHeader=function(buffer) {return{dwMagic:buffer[0],dwSize:buffer[1],dwFlags:x3dom.DDSLoader._readDDSFlags(buffer[2]),dwHeight:buffer[3],dwWidth:buffer[4],dwPitchOrLinearSize:buffer[5],dwDepth:buffer[6],dwMipMapCount:buffer[7],dwReserved1:"UNUSED",ddspf:{dwSize:buffer[19],dwFlags:x3dom.DDSLoader._readPFFlags(buffer[20]),dwFourCC:x3dom.DDSLoader.int32ToFourCC(buffer[21]),dwRGBBitCount:buffer[22],dwRBitMask:buffer[23],dwGBitMask:buffer[24],dwBBitMask:buffer[25],dwABitMask:buffer[26]},dwCaps:x3dom.DDSLoader._readCapsFlags(buffer[27]),dwCaps2:x3dom.DDSLoader._readCaps2Flags(buffer[28]),dwCaps3:"UNUSED",dwCaps4:"UNUSED",dwReserved2:"UNUSED"}};x3dom.DDSLoader._readHeader10=function(dds,buffer) {if(dds.header.ddspf.dwFourCC!="DX10") {return null;} return{dxgiFormat:buffer[0],resourceDimension:x3dom.DDSLoader._readResourceDimension(buffer[1]),miscFlags:x3dom.DDSLoader._readMiscFlags(buffer[2]),arraySize:buffer[3],miscFlags2:x3dom.DDSLoader._readMiscFlags2(buffer[4]),}};x3dom.DDSLoader._readMipmapCount=function(dds) {dds.numberOfMipmaps=(dds.header.dwFlags.DDSD_MIPMAPCOUNT)?dds.header.dwMipMapCount:1;} x3dom.DDSLoader._readType=function(dds) {if(dds.header.dwFlags.DDSD_DEPTH&&dds.header.dwCaps2.DDSCAPS2_VOLUME) {dds.type=32879;dds.numberOfImages=dds.header.dwCaps.DDSD_DEPTH;} else if(dds.header.dwCaps2.DDSCAPS2_CUBEMAP) {dds.type=34067;if(dds.header.dwCaps2.DDSCAPS2_CUBEMAP_POSITIVEX) {dds.targets.push(34069);} if(dds.header.dwCaps2.DDSCAPS2_CUBEMAP_NEGATIVEX) {dds.targets.push(34070);} if(dds.header.dwCaps2.DDSCAPS2_CUBEMAP_POSITIVEY) {dds.targets.push(34071);} if(dds.header.dwCaps2.DDSCAPS2_CUBEMAP_NEGATIVEY) {dds.targets.push(34072);} if(dds.header.dwCaps2.DDSCAPS2_CUBEMAP_POSITIVEZ) {dds.targets.push(34073);} if(dds.header.dwCaps2.DDSCAPS2_CUBEMAP_NEGATIVEZ) {dds.targets.push(34074);} dds.numberOfImages=dds.targets.length;} else {dds.type=3553;dds.targets.push(3553);dds.numberOfImages=dds.targets.length;}};x3dom.DDSLoader._readDDSFlags=function(dwFlags) {return{DDSD_CAPS:(dwFlags&0x1)?true:false,DDSD_HEIGHT:(dwFlags&0x2)?true:false,DDSD_WIDTH:(dwFlags&0x4)?true:false,DDSD_PITCH:(dwFlags&0x8)?true:false,DDSD_PIXELFORMAT:(dwFlags&0x1000)?true:false,DDSD_MIPMAPCOUNT:(dwFlags&0x20000)?true:false,DDSD_LINEARSIZE:(dwFlags&0x80000)?true:false,DDSD_DEPTH:(dwFlags&0x800000)?true:false}} x3dom.DDSLoader._readPFFlags=function(dwFlags) {return{DDPF_ALPHAPIXELS:(dwFlags&0x1)?true:false,DDPF_ALPHA:(dwFlags&0x2)?true:false,DDPF_FOURCC:(dwFlags&0x4)?true:false,DDPF_RGB:(dwFlags&0x40)?true:false,DDPF_YUV:(dwFlags&0x200)?true:false,DDPF_LUMINANCE:(dwFlags&0x20000)?true:false}} x3dom.DDSLoader._readCapsFlags=function(dwFlags) {return{DDSCAPS_COMPLEX:(dwFlags&0x8)?true:false,DDSCAPS_MIPMAP:(dwFlags&0x400000)?true:false,DDSCAPS_TEXTURE:(dwFlags&0x1000)?true:false}} x3dom.DDSLoader._readCaps2Flags=function(dwFlags) {return{DDSCAPS2_CUBEMAP:(dwFlags&0x200)?true:false,DDSCAPS2_CUBEMAP_POSITIVEX:(dwFlags&0x400)?true:false,DDSCAPS2_CUBEMAP_NEGATIVEX:(dwFlags&0x800)?true:false,DDSCAPS2_CUBEMAP_POSITIVEY:(dwFlags&0x1000)?true:false,DDSCAPS2_CUBEMAP_NEGATIVEY:(dwFlags&0x2000)?true:false,DDSCAPS2_CUBEMAP_POSITIVEZ:(dwFlags&0x4000)?true:false,DDSCAPS2_CUBEMAP_NEGATIVEZ:(dwFlags&0x8000)?true:false,DDSCAPS2_VOLUME:(dwFlags&0x20000)?true:false}} x3dom.DDSLoader._readResourceDimension=function(resourceDimension) {switch(resourceDimension) {case 0x0:return"D3D10_RESOURCE_DIMENSION_UNKNOWN";case 0x1:return"D3D10_RESOURCE_DIMENSION_BUFFER";case 0x2:return"D3D10_RESOURCE_DIMENSION_TEXTURE1D";case 0x3:return"D3D10_RESOURCE_DIMENSION_TEXTURE2D";case 0x4:return"D3D10_RESOURCE_DIMENSION_TEXTURE3D";}} x3dom.DDSLoader._readMiscFlags=function(miscFlag) {return{D3D11_RESOURCE_MISC_GENERATE_MIPS:(miscFlag&0x1)?true:false,D3D11_RESOURCE_MISC_SHARED:(miscFlag&0x2)?true:false,D3D11_RESOURCE_MISC_TEXTURECUBE:(miscFlag&0x4)?true:false,D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS:(miscFlag&0x10)?true:false,D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS:(miscFlag&0x20)?true:false,D3D11_RESOURCE_MISC_BUFFER_STRUCTURED:(miscFlag&0x40)?true:false,D3D11_RESOURCE_MISC_RESOURCE_CLAMP:(miscFlag&0x80)?true:false,D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX:(miscFlag&0x100)?true:false,D3D11_RESOURCE_MISC_GDI_COMPATIBLE:(miscFlag&0x200)?true:false,D3D11_RESOURCE_MISC_SHARED_NTHANDLE:(miscFlag&0x800)?true:false,D3D11_RESOURCE_MISC_RESTRICTED_CONTENT:(miscFlag&0x1000)?true:false,D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE:(miscFlag&0x2000)?true:false,D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE_DRIVER:(miscFlag&0x4000)?true:false,D3D11_RESOURCE_MISC_GUARDED:(miscFlag&0x8000)?true:false,D3D11_RESOURCE_MISC_TILE_POOL:(miscFlag&0x20000)?true:false,D3D11_RESOURCE_MISC_TILED:(miscFlag&0x40000)?true:false,D3D11_RESOURCE_MISC_HW_PROTECTED:(miscFlag&0x80000)?true:false,}} x3dom.DDSLoader._readMiscFlags2=function(miscFlag) {let miscFlags2={};switch(miscFlag) {case 0x0:miscFlags2.alphaMode="DDS_ALPHA_MODE_UNKNOWN";break;case 0x1:miscFlags2.alphaMode="DDS_ALPHA_MODE_UNKNOWN";break;case 0x2:miscFlags2.alphaMode="DDS_ALPHA_MODE_UNKNOWN";break;case 0x3:miscFlags2.alphaMode="DDS_ALPHA_MODE_UNKNOWN";break;case 0x4:miscFlags2.alphaMode="DDS_ALPHA_MODE_UNKNOWN";break;} return miscFlags2;} x3dom.DDSLoader._readData=function(dds,buffer,texture,options) {var offset=(dds.header10)?148:128;var byteArray,width,height;dds.width=dds.header.dwWidth;dds.height=dds.header.dwHeight;dds.generateMipmaps=(dds.numberOfMipmaps<=1&&!dds.isCompressed);for(let i=0;i>8)&0xff,(value>>16)&0xff,(value>>24)&0xff).replace(/[\x00]/g,"");};x3dom.DDSLoader.R8G8B8_To_B8G8R8=function(src) {var dst=new Uint8Array(src.length);for(var i=0;i>15)&0x1;var exponent=(interger>>10)&0x3ff;var fraction=interger&(Math.pow(2,10)-1);var result;if(exponent===0) {if(fraction===0) {result=0.0;} else {result=Math.pow(-1,sign)*fraction/Math.pow(2,10)*Math.pow(2,-14)}} result=Math.pow(-1,sign)*(1+fraction/Math.pow(2,10))*Math.pow(2,exponent-15);return result;} x3dom.DDSLoader.UI16_To_UI8_2=function(interger) {var float=x3dom.DDSLoader.UI16_To_F16(interger) return float/(float+1);} x3dom.DDSLoader.A4R4G4B4_To_A4B4G4R4=function(src){var a,r,g,b;var dst=new Uint16Array(src.length);for(var i=0;i>12)&0xf;r=(src[i]>>8)&0xf;g=(src[i]>>4)&0xf;b=(src[i])&0xf;var test=(r<<12)&(g<<8)&(b<<4)&(a);dst[i]=(r<<12)&(g<<8)&(b<<4)&(a);} return dst;};x3dom.DDSLoader.A1R5G5B5_To_A1B5G5R5=function(src) {var a,r,g,b;var dst=new Uint16Array(src.length);for(var i=0;i>15)&0x1;r=(src[i]>>10)&0x1f;g=(src[i]>>5)&0x5f;b=(src[i])&0x5f;dst[i]=(r<<11)&(g<<6)&(b<<1)&(a);} return dst;};x3dom.VRControllerManager=function() {this.leftInline=undefined;this.leftTransform=undefined;this.rightInline=undefined;this.rightTransform=undefined;this.leftGamepadIdx=undefined;this.rightGamepadIdx=undefined;this.vrDisplay=undefined;this.wasPresenting=false;this.controllers={"HTC Vive MV":{left:"https://x3dom.org/download/assets/vr/vive.glb",right:"https://x3dom.org/download/assets/vr/vive.glb",scaleFactor:new x3dom.fields.SFVec3f(40,40,40),offset:new x3dom.fields.SFVec3f(),axesScale:[1,1]},"Oculus Oculus Rift CV1":{left:"https://x3dom.org/download/assets/vr/oculus-touch-left.glb",right:"https://x3dom.org/download/assets/vr/oculus-touch-right.glb",scaleFactor:new x3dom.fields.SFVec3f(39.5,39.5,39.5),offset:new x3dom.fields.SFVec3f(),axesScale:[1,1]},"Oculus Go":{left:"https://x3dom.org/download/assets/vr/oculus-go.glb",right:"https://x3dom.org/download/assets/vr/oculus-go.glb",scaleFactor:new x3dom.fields.SFVec3f(1,1,1),offset:new x3dom.fields.SFVec3f(0.2,-0.3,-0.3),axesScale:[1,-1]},"Emulated HTC Vive DVT":{left:"https://x3dom.org/download/assets/vr/vive.glb",right:"https://x3dom.org/download/assets/vr/vive.glb",scaleFactor:new x3dom.fields.SFVec3f(40,40,40),offset:new x3dom.fields.SFVec3f(),axesScale:[1,1]},"WindowsMR DELL VISOR VR118":{left:"https://x3dom.org/download/assets/vr/microsoft-left.glb",right:"https://x3dom.org/download/assets/vr/microsoft-right.glb",scaleFactor:new x3dom.fields.SFVec3f(40,40,40),offset:new x3dom.fields.SFVec3f(),axesScale:[1,1]}} this._addInlines();this._addGamePadListeners();};x3dom.VRControllerManager.prototype._addGamePadListeners=function() {window.addEventListener("gamepadconnected",this._onGamePadConnected.bind(this));window.addEventListener("gamepaddisconnected",this._onGamePadDisconnected.bind(this));} x3dom.VRControllerManager.prototype._onGamePadConnected=function(e) {var gamepad=e.gamepad;navigator.getVRDisplays().then(function(displays){var display=displays[0];if(display&&gamepad.displayId==display.displayId) {var controller=this.controllers[display.displayName];if(!controller) {return;} if(gamepad.hand=="left") {this.leftGamepadIdx=gamepad.index;this.leftInline.setAttribute("url",controller.left);} else if(gamepad.hand=="right") {this.rightGamepadIdx=gamepad.index;this.rightInline.setAttribute("url",controller.right,controller.scaleFactor);}}}.bind(this));} x3dom.VRControllerManager.prototype._onGamePadDisconnected=function(e) {console.log(e);} x3dom.VRControllerManager.prototype._addInlines=function() {var x3dScene=document.querySelector("scene")||document.querySelector("Scene") if(x3dScene) {this.leftTransform=document.createElement("matrixtransform");this.leftInline=document.createElement("inline");this.rightTransform=document.createElement("matrixtransform");this.rightInline=document.createElement("inline");this.leftInline.setAttribute("render","false");this.rightInline.setAttribute("render","false");this.leftTransform.appendChild(this.leftInline);this.rightTransform.appendChild(this.rightInline);x3dScene.appendChild(this.leftTransform);x3dScene.appendChild(this.rightTransform);}} x3dom.VRControllerManager.prototype.fit=function(viewarea,vrDisplay) {var min=viewarea._scene._lastMin;var max=viewarea._scene._lastMax;var dia2=max.subtract(min).multiply(0.5);var bsr=dia2.length();var viewDir=viewarea.vrLeftViewMatrix.e2();var aspect=Math.min(viewarea._width/viewarea._height,1);var tanfov2=Math.tan(1.57/2.0);var dist=bsr/tanfov2/aspect;viewarea._movement=viewDir.multiply(-dist)} x3dom.VRControllerManager.prototype.update=function(viewarea,vrDisplay) {if(!vrDisplay||(vrDisplay&&!vrDisplay.isPresenting)) {if(this.wasPresenting) {this.leftInline.setAttribute("render","false");this.rightInline.setAttribute("render","false");this.wasPresenting=false;} return;} else {if(!this.wasPresenting) {this.leftInline.setAttribute("render","true");this.rightInline.setAttribute("render","true");this.fit(viewarea,vrDisplay);} this.wasPresenting=true;} var gamepads=navigator.getGamepads();var controller={};if(this.leftGamepadIdx!=undefined&&gamepads[this.leftGamepadIdx]) {var gamepad=gamepads[this.leftGamepadIdx];controller.left=gamepad;} if(this.rightGamepadIdx!=undefined&&gamepads[this.rightGamepadIdx]) {var gamepad=gamepads[this.rightGamepadIdx];controller.right=gamepad;} this.onUpdate(viewarea,vrDisplay,controller);} x3dom.VRControllerManager.prototype.onUpdate=function(viewarea,vrDisplay,controllers) {var transMat=new x3dom.fields.SFMatrix4f();var rotMat=new x3dom.fields.SFMatrix4f();var axes=[0,0];var axesScale=this.controllers[vrDisplay.displayName].axesScale;if(controllers.left) {axes[0]+=controllers.left.axes[0]*axesScale[0];axes[1]+=controllers.left.axes[1]*axesScale[1];if(controllers.left.buttons[1].pressed) {this.fit(viewarea);}} if(controllers.right) {axes[0]+=controllers.right.axes[0]*axesScale[0];axes[1]+=controllers.right.axes[1]*axesScale[1];if(controllers.right.buttons[1].pressed) {this.fit(viewarea);}} var dx=axes[0]*5;var dy=axes[1]*5;var viewDir=viewarea.vrLeftViewMatrix.e2();var rightDir=viewarea.vrLeftViewMatrix.e0();var d=(viewarea._scene._lastMax.subtract(viewarea._scene._lastMin)).length();d=((d-1);this.backend=this.x3dElem.getAttribute('backend');this.backend=(this.backend)?this.backend.toLowerCase():'none';this.canvas=this._createHTMLCanvas(x3dElem);x3dom.debug.appendElement(x3dElem);this.canvas.parent=this;this.gl=this._initContext(this.canvas,(this.backend.search("desktop")>=0),(this.backend.search("mobile")>=0),(this.backend.search("webgl2")>=0));this.backend='webgl';if(this.gl==null) {this.hasRuntime=false;this._createInitFailedDiv(x3dElem);return;} x3dom.caps.BACKEND=this.backend;var runtimeEnabled=x3dElem.getAttribute("runtimeEnabled");if(runtimeEnabled!==null) {this.hasRuntime=(runtimeEnabled.toLowerCase()=="true");} else {this.hasRuntime=x3dElem.hasRuntime;} this.showStat=x3dElem.getAttribute("showStat");this.stateViewer=new x3dom.States(x3dElem);if(this.showStat!==null&&this.showStat=="true") {this.stateViewer.display(true);} this.x3dElem.appendChild(this.stateViewer.viewer);this.showProgress=x3dElem.getAttribute("showProgress");this.progressDiv=this._createProgressDiv();this.progressDiv.style.display=(this.showProgress!==null&&this.showProgress=="true")?"flex":"none";this.x3dElem.appendChild(this.progressDiv);this.vrDiv=this._createVRDiv();this.x3dElem.appendChild(this.vrDiv);this.showTouchpoints=x3dElem.getAttribute("showTouchpoints");this.showTouchpoints=this.showTouchpoints?this.showTouchpoints:false;this.disableTouch=x3dElem.getAttribute("disableTouch");this.disableTouch=this.disableTouch?(this.disableTouch.toLowerCase()=="true"):false;this.disableKeys=x3dElem.getAttribute("disableKeys");this.disableKeys=this.disableKeys?(this.disableKeys.toLowerCase()=="true"):false;this.disableRightDrag=x3dElem.getAttribute("disableRightDrag");this.disableRightDrag=this.disableRightDrag?(this.disableRightDrag.toLowerCase()=="true"):false;this.disableLeftDrag=x3dElem.getAttribute("disableLeftDrag");this.disableLeftDrag=this.disableLeftDrag?(this.disableLeftDrag.toLowerCase()=="true"):false;this.disableMiddleDrag=x3dElem.getAttribute("disableMiddleDrag");this.disableMiddleDrag=this.disableMiddleDrag?(this.disableMiddleDrag.toLowerCase()=="true"):false;this.bindEventListeners();};x3dom.X3DCanvas.prototype.bindEventListeners=function(){var that=this;this.onMouseDown=function(evt){if(!this.isMulti){this.focus();this.classList.add('x3dom-canvas-mousedown');switch(evt.button){case 0:this.mouse_button=1;break;case 1:this.mouse_button=4;break;case 2:this.mouse_button=2;break;default:this.mouse_button=0;break;} if(evt.shiftKey){this.mouse_button=1;} if(evt.ctrlKey){this.mouse_button=4;} if(evt.altKey){this.mouse_button=2;} var pos=this.parent.mousePosition(evt);this.mouse_drag_x=pos.x;this.mouse_drag_y=pos.y;this.mouse_dragging=true;this.parent.doc.onMousePress(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);this.parent.doc.needRender=true;}} this.onMouseUp=function(evt){if(!this.isMulti){var prev_mouse_button=this.mouse_button;this.classList.remove('x3dom-canvas-mousedown');this.mouse_button=0;this.mouse_dragging=false;this.parent.doc.onMouseRelease(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button,prev_mouse_button);this.parent.doc.needRender=true;}} this.onMouseOver=function(evt){if(!this.isMulti){this.mouse_button=0;this.mouse_dragging=false;this.parent.doc.onMouseOver(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);this.parent.doc.needRender=true;}} this.onMouseAlt=function(evt){if(!this.isMulti){this.mouse_button=0;this.mouse_dragging=false;this.classList.remove('x3dom-canvas-mousedown');this.parent.doc.onMouseOut(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);this.parent.doc.needRender=true;}} this.onDoubleClick=function(evt){if(!this.isMulti){this.mouse_button=0;var pos=this.parent.mousePosition(evt);this.mouse_drag_x=pos.x;this.mouse_drag_y=pos.y;this.mouse_dragging=false;this.parent.doc.onDoubleClick(that.gl,this.mouse_drag_x,this.mouse_drag_y);this.parent.doc.needRender=true;}} this.onMouseMove=function(evt){if(!this.isMulti){var pos=this.parent.mousePosition(evt);if(pos.x!=that.lastMousePos.x||pos.y!=that.lastMousePos.y){that.lastMousePos=pos;this.mouse_drag_x=pos.x;this.mouse_drag_y=pos.y;if(this.mouse_dragging){if(evt.shiftKey){this.mouse_button=1;} if(evt.ctrlKey){this.mouse_button=4;} if(evt.altKey){this.mouse_button=2;} if(this.mouse_button==1&&!this.parent.disableLeftDrag||this.mouse_button==2&&!this.parent.disableRightDrag||this.mouse_button==4&&!this.parent.disableMiddleDrag) {this.parent.doc.onDrag(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);}} else{this.parent.doc.onMove(that.gl,this.mouse_drag_x,this.mouse_drag_y,this.mouse_button);} this.parent.doc.needRender=true;evt.preventDefault();evt.stopPropagation();}}} this.onDOMMouseScroll=function(evt){if(!this.isMulti){this.focus();var originalY=this.parent.mousePosition(evt).y;if(this.parent.doc._scene.getNavigationInfo()._vf.reverseScroll==true){this.mouse_drag_y-=2*evt.detail;} else{this.mouse_drag_y+=2*evt.detail;} this.parent.doc.onWheel(that.gl,this.mouse_drag_x,this.mouse_drag_y,originalY);this.parent.doc.needRender=true;evt.preventDefault();evt.stopPropagation();}} this.onKeyPress=function(evt){if(!this.parent.disableKeys){evt.preventDefault();this.parent.doc.onKeyPress(evt.charCode);} this.parent.doc.needRender=true;} this.onMouseWheel=function(evt){if(!this.isMulti){this.focus();var originalY=this.parent.mousePosition(evt).y;if(this.parent.doc._scene.getNavigationInfo()._vf.reverseScroll==true){this.mouse_drag_y+=0.1*evt.wheelDelta;} else{this.mouse_drag_y-=0.1*evt.wheelDelta;} this.parent.doc.onWheel(that.gl,this.mouse_drag_x,this.mouse_drag_y,originalY);this.parent.doc.needRender=true;evt.preventDefault();evt.stopPropagation();}} this.onKeyUp=function(evt){if(!this.parent.disableKeys){this.parent.doc.onKeyUp(evt.keyCode);} this.parent.doc.needRender=true;} this.onKeyDown=function(evt){if(!this.parent.disableKeys){this.parent.doc.onKeyDown(evt.keyCode);} this.parent.doc.needRender=true;} this.onVrDisplayPresentChange=function(evt){if(this.vrDisplay&&this.vrDisplay.isPresenting) {var leftEye=this.vrDisplay.getEyeParameters('left');var rightEye=this.vrDisplay.getEyeParameters('right');this._oldCanvasWidth=this.canvas.width;this._oldCanvasHeight=this.canvas.height;this.canvas.width=Math.max(leftEye.renderWidth,rightEye.renderWidth)*2;this.canvas.height=Math.max(leftEye.renderHeight,rightEye.renderHeight);this.gl.VRMode=2;this.doc.needRender=true;} else if(this.vrDisplay&&!this.vrDisplay.isPresenting) {this.canvas.width=this._oldCanvasWidth;this.canvas.height=this._oldCanvasHeight;this.vrFrameData=null;this.gl.VRMode=1;this.doc.needRender=true;}};if(this.canvas!==null&&this.gl!==null&&this.hasRuntime){this.canvas.mouse_dragging=false;this.canvas.mouse_button=0;this.canvas.mouse_drag_x=0;this.canvas.mouse_drag_y=0;this.canvas.isMulti=false;this.canvas.oncontextmenu=function(evt){evt.preventDefault();evt.stopPropagation();return false;};this.canvas.addEventListener("webglcontextlost",function(event){x3dom.debug.logError("WebGL context lost");event.preventDefault();},false);this.canvas.addEventListener("webglcontextrestored",function(event){x3dom.debug.logError("recover WebGL state and resources on context lost NYI");event.preventDefault();},false);window.addEventListener('vrdisplaypresentchange',this.onVrDisplayPresentChange.bind(this),false);this.canvas.addEventListener('mousedown',this.onMouseDown,false);this.canvas.addEventListener('mouseup',this.onMouseUp,false);this.canvas.addEventListener('mouseover',this.onMouseOver,false);this.canvas.addEventListener('mouseout',this.onMouseOut,false);this.canvas.addEventListener('dblclick',this.onDoubleClick,false);this.canvas.addEventListener('mousemove',this.onMouseMove,false);this.canvas.addEventListener('DOMMouseScroll',this.onDOMMouseScroll,false);this.canvas.addEventListener('mousewheel',this.onMouseWheel,false);this.canvas.addEventListener('keypress',this.onKeyPress,true);this.canvas.addEventListener('keyup',this.onKeyUp,true);this.canvas.addEventListener('keydown',this.onKeyDown,true);var touches={numTouches:0,firstTouchTime:new Date().getTime(),firstTouchPoint:new x3dom.fields.SFVec2f(0,0),lastPos:new x3dom.fields.SFVec2f(),lastDrag:new x3dom.fields.SFVec2f(),lastMiddle:new x3dom.fields.SFVec2f(),lastSquareDistance:0,lastAngle:0,lastLayer:[],examineNavType:1,calcAngle:function(vector) {var rotation=vector.normalize().dot(new x3dom.fields.SFVec2f(1,0));rotation=Math.acos(rotation);if(vector.y<0) rotation=Math.PI+(Math.PI-rotation);return rotation;},disableTouch:this.disableTouch,visMarker:this.showTouchpoints,visMarkerBag:[],visualizeTouches:function(evt) {if(!this.visMarker) return;var touchBag=[];var marker=null;for(var i=0;i=0){marker=document.getElementById("visMarker"+id);marker.style.left=(evt.touches[i].pageX)+"px";marker.style.top=(evt.touches[i].pageY)+"px";} else{marker=document.createElement("div");marker.appendChild(document.createTextNode("#"+id));marker.id="visMarker"+id;marker.className="x3dom-touch-marker";document.body.appendChild(marker);index=this.visMarkerBag.length;this.visMarkerBag[index]=id;} touchBag.push(id);} for(var j=this.visMarkerBag.length-1;j>=0;j--){var oldId=this.visMarkerBag[j];if(touchBag.indexOf(oldId)<0){this.visMarkerBag.splice(j,1);marker=document.getElementById("visMarker"+oldId);document.body.removeChild(marker);}}}};var touchStartHandler=function(evt,doc) {this.isMulti=true;evt.preventDefault();touches.visualizeTouches(evt);this.focus();if(doc==null) doc=this.parent.doc;var navi=doc._scene.getNavigationInfo();switch(navi.getType()){case"examine":touches.examineNavType=1;break;case"turntable":touches.examineNavType=2;break;default:touches.examineNavType=0;break;} touches.lastLayer=[];var i,pos;for(i=0;i=2){touches.numTouches=2;var touch0=new x3dom.fields.SFVec2f(evt.touches[0].screenX,evt.touches[0].screenY);var touch1=new x3dom.fields.SFVec2f(evt.touches[1].screenX,evt.touches[1].screenY);var distance=touch1.subtract(touch0);var middle=distance.multiply(0.5).add(touch0);var squareDistance=distance.dot(distance);touches.lastMiddle=middle;touches.lastSquareDistance=squareDistance;touches.lastAngle=touches.calcAngle(distance);touches.lastPos=this.parent.mousePosition(evt.touches[0]);} doc._scene.updateVolume();if(touches.examineNavType==1){for(i=0;i=2){touch0=new x3dom.fields.SFVec2f(evt.touches[0].screenX,evt.touches[0].screenY);touch1=new x3dom.fields.SFVec2f(evt.touches[1].screenX,evt.touches[1].screenY);distance=touch1.subtract(touch0);middle=distance.multiply(0.5).add(touch0);squareDistance=distance.dot(distance);deltaMiddle=middle.subtract(touches.lastMiddle);deltaZoom=squareDistance-touches.lastSquareDistance;deltaMove=new x3dom.fields.SFVec3f(deltaMiddle.x/screen.width,-deltaMiddle.y/screen.height,deltaZoom/(screen.width*screen.height*0.2));var rotation=touches.calcAngle(distance);var angleDelta=touches.lastAngle-rotation;touches.lastAngle=rotation;rotMatrix=x3dom.fields.SFMatrix4f.rotationZ(angleDelta);touches.lastMiddle=middle;touches.lastSquareDistance=squareDistance;doc.onMoveView(that.gl,evt,touches,deltaMove,rotMatrix);}} else if(evt.touches.length){if(touches.examineNavType==2&&evt.touches.length>=2){touch0=new x3dom.fields.SFVec2f(evt.touches[0].screenX,evt.touches[0].screenY);touch1=new x3dom.fields.SFVec2f(evt.touches[1].screenX,evt.touches[1].screenY);distance=touch1.subtract(touch0);squareDistance=distance.dot(distance);deltaZoom=(squareDistance-touches.lastSquareDistance)/(0.1*(screen.width+screen.height));touches.lastPos.y+=deltaZoom;touches.lastSquareDistance=squareDistance;doc.onDrag(that.gl,touches.lastPos.x,touches.lastPos.y,2);} else{pos=this.parent.mousePosition(evt.touches[0]);doc.onDrag(that.gl,pos.x,pos.y,1);}} doc.needRender=true;};var touchEndHandler=function(evt,doc) {this.isMulti=false;evt.preventDefault();touches.visualizeTouches(evt);if(doc==null) doc=this.parent.doc;doc._viewarea._isMoving=false;if(touches.numTouches==2&&evt.touches.length==1) touches.lastDrag=new x3dom.fields.SFVec2f(evt.touches[0].screenX,evt.touches[0].screenY);if(evt.touches.length==0) {var affectedPointingSensorsList=doc._nodeBag.affectedPointingSensors;for(var i=0;i=0){x3dom.debug.logWarning("The width attribute is to be specified in pixels not in percent.");} canvas.style.width=w;x3dElem.style.width=w;canvas.setAttribute("width",w);} if((h=x3dElem.getAttribute("height"))!==null){if(h.indexOf("%")>=0){x3dom.debug.logWarning("The height attribute is to be specified in pixels not in percent.");} canvas.style.height=h;x3dElem.style.height=h;canvas.setAttribute("height",h);} canvas.setAttribute("tabindex","0");return canvas;};x3dom.X3DCanvas.prototype._watchForResize=function(){if(this.vrDisplay&&this.vrDisplay.isPresenting) {return;} var new_dim=[parseInt(x3dom.getStyle(this.canvas,"width")),parseInt(x3dom.getStyle(this.canvas,"height"))];if((this._current_dim[0]!=new_dim[0])||(this._current_dim[1]!=new_dim[1])){this._current_dim=new_dim;this.x3dElem.setAttribute("width",new_dim[0]+"px");this.x3dElem.setAttribute("height",new_dim[1]+"px");}};x3dom.X3DCanvas.prototype._createProgressDiv=function(){var progressDiv=document.createElement('div');progressDiv.setAttribute("class","x3dom-progress");var spinnerDiv=document.createElement('div');spinnerDiv.setAttribute("class","x3dom-progress-spinner");progressDiv.appendChild(spinnerDiv);var text=document.createElement('div');text.setAttribute("id","x3domProgessCount");text.appendChild(document.createTextNode('Loading...'));progressDiv.appendChild(text);progressDiv.oncontextmenu=progressDiv.onmousedown=function(evt){evt.preventDefault();evt.stopPropagation();return false;};return progressDiv;};x3dom.X3DCanvas.prototype._createVRDiv=function(){var vrDiv=document.createElement('div');vrDiv.setAttribute("class","x3dom-vr");vrDiv.onclick=function() {this.x3dElem.runtime.toggleVR();}.bind(this);vrDiv.oncontextmenu=function(evt){evt.preventDefault();evt.stopPropagation();return false;};return vrDiv;};x3dom.X3DCanvas.prototype.mousePosition=function(evt) {var rect=evt.target.getBoundingClientRect();var offsetX=Math.round(evt.clientX-rect.left)*this.devicePixelRatio;var offsetY=Math.round(evt.clientY-rect.top)*this.devicePixelRatio;return new x3dom.fields.SFVec2f(offsetX,offsetY);};x3dom.X3DCanvas.prototype.tick=function(timestamp) {var that=this;this._elapsedTime=(this._totalTime)?timestamp-this._totalTime:0;this._totalTime=timestamp;var runtime=this.x3dElem.runtime;var d=new Date().getTime();var diff=d-this.lastTimeFPSWasTaken;var fps=1000.0/(d-this.fps_t0);this.fps_t0=d;this.doc.advanceTime(d/1000.0);var animD=new Date().getTime()-d;if(this.doc.hasAnimationStateChanged()) {if(this.doc.isAnimating()) {runtime.onAnimationStarted();} else {runtime.onAnimationFinished();}} if(this.doc.needRender){if(diff>=1000){runtime.fps=this.framesSinceLastTime/(diff/1000.0);runtime.addMeasurement('FPS',runtime.fps);this.framesSinceLastTime=0;this.lastTimeFPSWasTaken=d;} this.framesSinceLastTime++;runtime.addMeasurement('ANIM',animD);if(runtime.isReady==false){runtime.ready();runtime.isReady=true;} runtime.enterFrame({"total":this._totalTime,"elapsed":this._elapsedTime});if(this.vrDisplay&&this.vrDisplay.isPresenting) {if(!this.vrFrameData) {this.vrFrameData=new VRFrameData();} this.vrDisplay.getFrameData(this.vrFrameData);} else {this.doc.needRender=false;} this.doc.render(this.gl,this.vrFrameData,this.vrDisplay);if(!this.doc._scene._vf.doPickPass) {runtime.removeMeasurement('PICKING');} runtime.exitFrame({"total":this._totalTime,"elapsed":this._elapsedTime});if(this.vrDisplay&&this.vrDisplay.isPresenting) {this.vrDisplay.submitFrame();}} if(this.progressDiv){if(this.doc.downloadCount>0){runtime.addInfo("#LOADS:",this.doc.downloadCount);}else{runtime.removeInfo("#LOADS:");} if(this.doc.properties.getProperty("showProgress")!=='false'){if(this.progressDiv){var count=Math.max(+this.doc.downloadCount,0);this.progressDiv.childNodes[1].textContent=""+count;if(this.doc.downloadCount>0){this.progressDiv.style.opacity='1';}else{this.progressDiv.style.opacity='0';}}}else{this.progressDiv.style.opacity='0';}} if(this.doc.downloadCount<=0&&this.doc.previousDownloadCount>0) {var evt;if(document.createEvent){evt=document.createEvent("Events");evt.initEvent("downloadsfinished",true,true);that.x3dElem.dispatchEvent(evt);}else if(document.createEventObject){evt=document.createEventObject();that.x3dElem.fireEvent("ondownloadsfinished",evt);}} this.doc.previousDownloadCount=this.doc.downloadCount;};x3dom.X3DCanvas.prototype.load=function(uri,sceneElemPos,settings){this.doc=new x3dom.X3DDocument(this.canvas,this.gl,settings);var x3dCanvas=this;this.doc.onload=function(){if(x3dCanvas.hasRuntime){(function mainloop(timestamp){if(x3dCanvas.doc&&x3dCanvas.x3dElem.runtime){x3dCanvas._watchForResize();x3dCanvas.tick(timestamp);if(navigator.getVRDisplays) {if(x3dCanvas.vrDisplay) {x3dCanvas.vrDisplay.requestAnimationFrame(mainloop,x3dCanvas);} else {if(!this.vrDisplayPromise) {this.vrDisplayPromise=navigator.getVRDisplays();} this.vrDisplayPromise.then(function(displays){x3dCanvas.vrDisplay=displays[0];if(x3dCanvas.vrDisplay) {x3dCanvas.vrDisplay.requestAnimationFrame(mainloop,x3dCanvas);x3dCanvas.vrDiv.style.display="block";} else {window.requestAnimFrame(mainloop,x3dCanvas);}});}} else {window.requestAnimFrame(mainloop,x3dCanvas);}}})();}else{x3dCanvas.tick();}};this.x3dElem.render=function(){if(x3dCanvas.hasRuntime){x3dCanvas.doc.needRender=true;}else{x3dCanvas.doc.render(x3dCanvas.gl);}};this.x3dElem.context=x3dCanvas.gl.ctx3d;this.doc.onerror=function(){alert('Failed to load X3D document');};this.doc.load(uri,sceneElemPos);};x3dom.runtime={};x3dom.Runtime=function(doc,canvas){this.doc=doc;this.canvas=canvas;this.config={};this.isReady=false;this.fps=0;this.VRMode=false;this.states={measurements:[],infos:[]};};x3dom.Runtime.prototype.addMeasurement=function(title,value){this.states.measurements[title]=value;};x3dom.Runtime.prototype.removeMeasurement=function(title){if(this.states.measurements[title]){delete this.states.measurements[title];}};x3dom.Runtime.prototype.addInfo=function(title,value){this.states.infos[title]=value;};x3dom.Runtime.prototype.removeInfo=function(title){delete this.states.infos[title];};x3dom.Runtime.prototype.initialize=function(doc,canvas){this.doc=doc;this.canvas=canvas;this.config={};this.isReady=false;this.fps=0;};x3dom.Runtime.prototype.noBackendFound=function(){x3dom.debug.logInfo('No backend found. Unable to render.');};x3dom.Runtime.prototype.ready=function(){x3dom.debug.logInfo('System ready.');};x3dom.Runtime.prototype.enterFrame=function(){};x3dom.Runtime.prototype.exitFrame=function(){};x3dom.Runtime.prototype.triggerRedraw=function(){this.canvas.doc.needRender=true;};x3dom.Runtime.prototype.getActiveBindable=function(typeName){var stacks;var i,current,result;var type;stacks=this.canvas.doc._bindableBag._stacks;result=[];type=x3dom.nodeTypesLC[typeName.toLowerCase()];if(!type){x3dom.debug.logError('No node of type "'+typeName+'" found.');return null;} for(i=0;imax.x)?pos2D[0]:max.x;max.y=(pos2D[1]>max.y)?pos2D[1]:max.y;} var rect={x:min.x,y:min.y,width:max.x-min.x,height:max.y-min.y};return rect;};x3dom.Runtime.prototype.calcClientPos=function(wx,wy,wz){var elem=this.canvas.canvas.offsetParent;if(!elem){x3dom.debug.logError("Can't calc client pos without offsetParent.");return[0,0];} var canvasPos=elem.getBoundingClientRect();var mousePos=this.calcCanvasPos(wx,wy,wz);var compStyle=document.defaultView.getComputedStyle(elem,null);var paddingLeft=parseFloat(compStyle.getPropertyValue('padding-left'));var borderLeftWidth=parseFloat(compStyle.getPropertyValue('border-left-width'));var paddingTop=parseFloat(compStyle.getPropertyValue('padding-top'));var borderTopWidth=parseFloat(compStyle.getPropertyValue('border-top-width'));var x=canvasPos.left+paddingLeft+borderLeftWidth+mousePos[0];var y=canvasPos.top+paddingTop+borderTopWidth+mousePos[1];return[x,y];};x3dom.Runtime.prototype.getScreenshot=function(){var url="";var backend=this.canvas.backend;var canvas=this.canvas.canvas;if(canvas){if(backend=="flash"){url=canvas.getScreenshot();}else{var canvas2d=document.createElement("canvas");canvas2d.width=canvas.width;canvas2d.height=canvas.height;var ctx=canvas2d.getContext("2d");ctx.drawImage(canvas,0,0,canvas.width,canvas.height);ctx.scale(1,-1);ctx.translate(0,-canvas.height);url=canvas2d.toDataURL();}} return url;};x3dom.Runtime.prototype.getCanvas=function(){return this.canvas.canvas;};x3dom.Runtime.prototype.lightMatrix=function(){this.canvas.doc._viewarea.getLightMatrix();};x3dom.Runtime.prototype.resetView=function(){this.canvas.doc._viewarea.resetView();};x3dom.Runtime.prototype.lightView=function(){if(this.canvas.doc._nodeBag.lights.length>0){this.canvas.doc._viewarea.animateTo(this.canvas.doc._viewarea.getLightMatrix()[0],this.canvas.doc._scene.getViewpoint());return true;}else{x3dom.debug.logInfo("No lights to navigate to.");return false;}};x3dom.Runtime.prototype.uprightView=function(){this.canvas.doc._viewarea.uprightView();};x3dom.Runtime.prototype.fitAll=function(updateCenterOfRotation){if(updateCenterOfRotation===undefined){updateCenterOfRotation=true;} var scene=this.canvas.doc._scene;scene.updateVolume();this.canvas.doc._viewarea.fit(scene._lastMin,scene._lastMax,updateCenterOfRotation);};x3dom.Runtime.prototype.fitObject=function(obj,updateCenterOfRotation){if(obj&&obj._x3domNode){if(updateCenterOfRotation===undefined){updateCenterOfRotation=true;} var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();var vol=obj._x3domNode.getVolume();vol.getBounds(min,max);var mat=obj._x3domNode.getCurrentTransform();min=mat.multMatrixPnt(min);max=mat.multMatrixPnt(max);if(x3dom.isa(obj._x3domNode,x3dom.nodeTypes.X3DTransformNode)){var invMat=obj._x3domNode._trafo.inverse();min=invMat.multMatrixPnt(min);max=invMat.multMatrixPnt(max);} this.canvas.doc._viewarea.fit(min,max,updateCenterOfRotation);}};x3dom.Runtime.prototype.showAll=function(axis,updateCenterOfRotation){this.canvas.doc._viewarea.showAll(axis,updateCenterOfRotation);};x3dom.Runtime.prototype.showObject=function(obj,axis){if(obj&&obj._x3domNode){if(axis===undefined)axis="negZ";var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();var vol=obj._x3domNode.getVolume();vol.getBounds(min,max);var mat=obj._x3domNode.getCurrentTransform();min=mat.multMatrixPnt(min);max=mat.multMatrixPnt(max);var viewarea=this.canvas.doc._viewarea;var focalLen=(viewarea._widthx3dom.fields.Eps){focalLen/=ta;} var w=viewarea._width-1;var h=viewarea._height-1;var frame=0.25;var minScreenPos=new x3dom.fields.SFVec2f(frame*w,frame*h);frame=0.75;var maxScreenPos=new x3dom.fields.SFVec2f(frame*w,frame*h);var dia2=max.subtract(min).multiply(0.5);var rw=dia2.length();var pc=min.add(dia2);var vc=maxScreenPos.subtract(minScreenPos).multiply(0.5);var rs=1.5*vc.length();vc=vc.add(minScreenPos);var dist=1.0;if(rs>x3dom.fields.Eps){dist=(rw/rs)*Math.sqrt(vc.x*vc.x+vc.y*vc.y+focalLen*focalLen);} n0=mat.multMatrixVec(n0).normalize();n0=n0.multiply(dist);var p0=pc.add(n0);var qDir=x3dom.fields.Quaternion.rotateFromTo(new x3dom.fields.SFVec3f(0,0,1),n0);var R=qDir.toMatrix();var T=x3dom.fields.SFMatrix4f.translation(p0.negate());var M=x3dom.fields.SFMatrix4f.translation(p0);M=M.mult(R).mult(T).mult(M);var viewmat=M.inverse();viewarea.animateTo(viewmat,viewpoint);}};x3dom.Runtime.prototype.animateViewpointTo=function(target,duration){var viewarea=this.canvas.doc._viewarea;var viewpoint=this.canvas.doc._scene.getViewpoint();if(target._x3domNode!=undefined) {target=target._x3domNode} viewarea.animateTo(target,viewpoint,duration);};x3dom.Runtime.prototype.getCenter=function(domNode){if(domNode&&domNode._x3domNode&&(this.isA(domNode,"X3DShapeNode")||this.isA(domNode,"X3DGeometryNode"))){return domNode._x3domNode.getCenter();} return null;};x3dom.Runtime.prototype.getCurrentTransform=function(domNode){if(domNode&&domNode._x3domNode){return domNode._x3domNode.getCurrentTransform();} return null;};x3dom.Runtime.prototype.getBBox=function(domNode){if(domNode&&domNode._x3domNode&&this.isA(domNode,"X3DBoundedObject")){var vol=domNode._x3domNode.getVolume();return{min:x3dom.fields.SFVec3f.copy(vol.min),max:x3dom.fields.SFVec3f.copy(vol.max)}} return null;};x3dom.Runtime.prototype.getSceneBBox=function(){var scene=this.canvas.doc._scene;scene.updateVolume();return{min:x3dom.fields.SFVec3f.copy(scene._lastMin),max:x3dom.fields.SFVec3f.copy(scene._lastMax)}};x3dom.Runtime.prototype.debug=function(show){var doc=this.canvas.doc;if(doc._viewarea._visDbgBuf===undefined){doc._viewarea._visDbgBuf=(doc._x3dElem.getAttribute("showLog")==='true');} if(arguments.length>0){if(show===true){doc._viewarea._visDbgBuf=true;x3dom.debug.logContainer.style.display="block";}else{doc._viewarea._visDbgBuf=false;x3dom.debug.logContainer.style.display="none";}}else{doc._viewarea._visDbgBuf=!doc._viewarea._visDbgBuf;x3dom.debug.logContainer.style.display=(doc._viewarea._visDbgBuf==true)?"block":"none";} doc.needRender=true;return doc._viewarea._visDbgBuf;};x3dom.Runtime.prototype.navigationType=function(){return this.canvas.doc._scene.getNavigationInfo().getType();};x3dom.Runtime.prototype.noNav=function(){this.canvas.doc._scene.getNavigationInfo().setType("none");};x3dom.Runtime.prototype.examine=function(){this.canvas.doc._scene.getNavigationInfo().setType("examine");};x3dom.Runtime.prototype.turnTable=function(){this.canvas.doc._scene.getNavigationInfo().setType("turntable");};x3dom.Runtime.prototype.fly=function(){this.canvas.doc._scene.getNavigationInfo().setType("fly");};x3dom.Runtime.prototype.freeFly=function(){this.canvas.doc._scene.getNavigationInfo().setType("freefly");};x3dom.Runtime.prototype.lookAt=function(){this.canvas.doc._scene.getNavigationInfo().setType("lookat");};x3dom.Runtime.prototype.lookAround=function(){this.canvas.doc._scene.getNavigationInfo().setType("lookaround");};x3dom.Runtime.prototype.walk=function(){this.canvas.doc._scene.getNavigationInfo().setType("walk");};x3dom.Runtime.prototype.game=function(){this.canvas.doc._scene.getNavigationInfo().setType("game");};x3dom.Runtime.prototype.helicopter=function(){this.canvas.doc._scene.getNavigationInfo().setType("helicopter");};x3dom.Runtime.prototype.resetExamin=function(){var viewarea=this.canvas.doc._viewarea;viewarea._rotMat=x3dom.fields.SFMatrix4f.identity();viewarea._transMat=x3dom.fields.SFMatrix4f.identity();viewarea._movement=new x3dom.fields.SFVec3f(0,0,0);viewarea._needNavigationMatrixUpdate=true;this.canvas.doc.needRender=true;};x3dom.Runtime.prototype.disableKeys=function(){this.canvas.disableKeys=true;};x3dom.Runtime.prototype.enableKeys=function(){this.canvas.disableKeys=false;};x3dom.Runtime.prototype.disableLeftDrag=function(){this.canvas.disableLeftDrag=true;};x3dom.Runtime.prototype.enableLeftDrag=function(){this.canvas.disableLeftDrag=false;};x3dom.Runtime.prototype.disableRightDrag=function(){this.canvas.disableRightDrag=true;};x3dom.Runtime.prototype.enableRightDrag=function(){this.canvas.disableRightDrag=false;};x3dom.Runtime.prototype.disableMiddleDrag=function(){this.canvas.disableMiddleDrag=true;};x3dom.Runtime.prototype.enableMiddleDrag=function(){this.canvas.disableMiddleDrag=false;};x3dom.Runtime.prototype.togglePoints=function(lines){var doc=this.canvas.doc;var mod=(lines===true)?3:2;doc._viewarea._points=++doc._viewarea._points%mod;doc.needRender=true;return doc._viewarea._points;};x3dom.Runtime.prototype.pickRect=function(x1,y1,x2,y2){return this.canvas.doc.onPickRect(this.canvas.gl,x1,y1,x2,y2);};x3dom.Runtime.prototype.pickMode=function(options){if(options&&options.internal===true){return this.canvas.doc._scene._vf.pickMode;} return this.canvas.doc._scene._vf.pickMode.toLowerCase();};x3dom.Runtime.prototype.changePickMode=function(type){type=type.toLowerCase();switch(type){case'idbuf':type='idBuf';break;case'idbuf24':type='idBuf24';break;case'idbufid':type='idBufId';break;case'texcoord':type='texCoord';break;case'color':type='color';break;case'box':type='box';break;default:x3dom.debug.logWarning("Switch pickMode to "+type+' unknown intersect type');type=undefined;} if(type!==undefined){this.canvas.doc._scene._vf.pickMode=type;x3dom.debug.logInfo("Switched pickMode to '"+type+"'.");return true;} return false;};x3dom.Runtime.prototype.speed=function(newSpeed){var navi=this.canvas.doc._scene.getNavigationInfo();if(newSpeed){navi._vf.speed=newSpeed;x3dom.debug.logInfo("Changed navigation speed to "+navi._vf.speed);} return navi._vf.speed;};x3dom.Runtime.prototype.zoom=function(zoomAmount){this.canvas.doc._viewarea.zoom(zoomAmount);this.canvas.doc.needRender=true;};x3dom.Runtime.prototype.statistics=function(mode){var states=this.canvas.stateViewer;if(states){this.canvas.doc.needRender=true;if(mode===true){states.display(mode);return true;}else if(mode===false){states.display(mode);return false;}else{states.display(!states.active);return states.active;}} return false;};x3dom.Runtime.prototype.processIndicator=function(mode){var processDiv=this.canvas.progressDiv;if(processDiv){if(mode===true){processDiv.style.display='flex';return true;}else if(mode===false){processDiv.style.display='none';return false;} return processDiv.style.display!='none'} return false;};x3dom.Runtime.prototype.properties=function(){return this.canvas.doc.properties;};x3dom.Runtime.prototype.backendName=function(){return this.canvas.backend;};x3dom.Runtime.prototype.getFPS=function(){return this.fps;};x3dom.Runtime.prototype.isA=function(domNode,nodeType){var inherits=false;if(nodeType&&domNode&&domNode._x3domNode){if(nodeType===""){nodeType="X3DNode";} inherits=x3dom.isa(domNode._x3domNode,x3dom.nodeTypesLC[nodeType.toLowerCase()]);} return inherits;};x3dom.Runtime.prototype.getPixelScale=function(){var vp=this.viewpoint();if(!x3dom.isa(vp,x3dom.nodeTypes.OrthoViewpoint)){x3dom.debug.logError("getPixelScale is only implemented for orthographic Viewpoints");return null;} var zoomLevel=vp.getZoom();var left=zoomLevel[0];var bottom=zoomLevel[1];var right=zoomLevel[2];var top=zoomLevel[3];var x=right-left;var y=top-bottom;var pixelScaleX=x/this.getWidth();var pixelScaleY=y/this.getHeight();return new x3dom.fields.SFVec3f(pixelScaleX,pixelScaleY,0.0);};x3dom.Runtime.prototype.onAnimationStarted=function(){};x3dom.Runtime.prototype.onAnimationFinished=function(){};x3dom.Runtime.prototype.enterVR=function(){if(this.canvas.vrDisplay&&!this.canvas.vrDisplay.isPresenting) {this.canvas.vrDisplay.requestPresent([{source:this.canvas.canvas}]).then(function(){this.canvas.doc.needRender=true;}.bind(this));}};x3dom.Runtime.prototype.exitVR=function(){if(this.canvas.vrDisplay&&this.canvas.vrDisplay.isPresenting) {this.canvas.vrDisplay.exitPresent();}};x3dom.Runtime.prototype.toggleVR=function(){if(this.canvas.vrDisplay&&!this.canvas.vrDisplay.isPresenting) {this.enterVR();} else if(this.canvas.vrDisplay&&this.canvas.vrDisplay.isPresenting) {this.exitVR();}};x3dom.Runtime.prototype.toggleProjection=function(perspViewID,orthoViewID){var dist;var factor=2.2;var runtime=document.getElementById("x3d").runtime;var navInfo=runtime.canvas.doc._scene.getNavigationInfo();var speed=navInfo._vf.transitionTime;var persp=document.getElementById(perspViewID)._x3domNode;var ortho=document.getElementById(orthoViewID)._x3domNode;navInfo._vf.transitionTime=0;ortho._bindAnimation=false;persp._bindAnimation=false;if(persp._vf.isActive){ortho._viewMatrix=persp._viewMatrix;document.getElementById(orthoViewID).setAttribute("set_bind","true");dist=persp._viewMatrix.e3().length()/factor;ortho.setZoom(dist);}else if(ortho._vf.isActive){persp._viewMatrix=ortho._viewMatrix;document.getElementById(perspViewID).setAttribute("set_bind","true");dist=ortho._fieldOfView[2]*-factor;var translation=ortho._viewMatrix.e2().normalize().multiply(dist);persp._viewMatrix.setTranslate(translation);} navInfo._vf.transitionTime=speed;ortho._bindAnimation=true;persp._bindAnimation=true;return(persp._vf.isActive)?0:1;};x3dom.Runtime.prototype.replaceWorld=function(scene){var x3dElement=this.doc.cloneNode(false);var child,name;while(child=scene.firstChild){name=child.nodeType===1?child.localName.toUpperCase():null;if(name=='HEAD'||name=='SCENE')x3dElement.appendChild(child);else{child.remove();}} this.doc.parentNode.replaceChild(x3dElement,this.doc);this.doc=x3dElement;x3dom.reload();return;};x3dom.Runtime.prototype.createX3DFromJS=function(jsobject,optionalURL){if(optionalURL){jsobject=x3dom.protoExpander.prototypeExpander(optionalURL,jsobject);} var jsonParser=new x3dom.JSONParser();return jsonParser.parseJavaScript(jsobject);};x3dom.Runtime.prototype.createX3DFromString=function(jsonOrXML,optionalURL){try{var jsobject=JSON.parse(jsonOrXML);return this.createX3DFromJS(jsobject,optionalURL);}catch(e){var parser=new DOMParser();var doc=parser.parseFromString(jsonOrXML,'application/xml');var scene=doc.querySelector('X3D');if(scene==null){doc=parser.parseFromString(jsonOrXML,'text/html');scene=doc.querySelector('X3D');} return scene;}};x3dom.Runtime.prototype.createX3DFromURLPromise=function(url,optionalURL){this.canvas.doc.incrementDownloads();that=this;return fetch(url).then(function(r){return r.text();}).then(function(text){that.canvas.doc.decrementDownloads();return that.createX3DFromString(text,optionalURL);}).catch(function(r){that.canvas.doc.decrementDownloads();x3dom.debug.logError('fetch failed: '+r);return null;});};x3dom.Runtime.prototype.loadURL=function(url,optionalURL){that=this;this.createX3DFromURLPromise(url,optionalURL).then(function(x3d){if(x3d!=null)that.replaceWorld(x3d);else x3dom.debug.logError("loadURL: could not fetch or parse "+url);});};x3dom.userAgentFeature={supportsDOMAttrModified:false};(function loadX3DOM(){"use strict";var onload=function(){var i,j;var x3ds_unfiltered=document.getElementsByTagName('X3D');var x3ds=[];for(i=0;i" +x3dom.versionInfo.revision+", "+"Date "+x3dom.versionInfo.date);} x3dom.debug.logInfo("Found "+x3ds.length+" X3D and nodes...");var x3d_element;var x3dcanvas;var altDiv,altP,aLnk,altImg;var t0,t1;for(i=0;i2.3){font_size=2.3;}} var textX,textY;var paragraph=this.node._vf.string;var maxExtent=this.node._vf.maxExtent;var lengths=[];var text_canvas=document.createElement('canvas');text_canvas.dir=leftToRight;var x3dToPx=42;var textHeight=font_size*x3dToPx;var textAlignment=font_justify;document.body.appendChild(text_canvas);var text_ctx=text_canvas.getContext('2d');text_ctx.font=font_style+" "+textHeight+"px "+font_family;var maxWidth=0,pWidth,pLength;var i,j;for(i=0;imaxWidth){maxWidth=pWidth;} pLength=this.node._vf.length[i]|0;if(maxExtent>0&&(pLength>maxExtent||pLength==0)){pLength=maxExtent;} lengths[i]=pLength<=0?pWidth:pLength*x3dToPx;} var canvas_extra=0.25*textHeight;var txtW=maxWidth;var txtH=textHeight*font_spacing*paragraph.length+canvas_extra;textX=0;textY=0;var x_offset=0,y_offset=0,baseLine='top';switch(font_justify){case"center":x_offset=-txtW/2;textX=txtW/2;break;case"left":x_offset=0;textX=0;break;case"right":x_offset=-txtW;textX=txtW;break;} switch(minor_alignment){case"MIDDLE":y_offset=txtH/2-canvas_extra/2;break;case"BEGIN":y_offset=topToBottom?0:txtH-canvas_extra;baseLine=topToBottom?'top':'bottom';textY=topToBottom?0:textHeight;break;case"FIRST":y_offset=topToBottom?textHeight:txtH-canvas_extra;baseLine=topToBottom?'alphabetic':'bottom';textY=topToBottom?textHeight:textHeight;break;case"END":y_offset=topToBottom?txtH-canvas_extra:0;baseLine=topToBottom?'bottom':'top';textY=topToBottom?textHeight:0;break;} var pxToX3d=1/42.0;var w=txtW*pxToX3d;var h=txtH*pxToX3d;x_offset*=pxToX3d;y_offset*=pxToX3d;text_canvas.width=txtW*oversample;text_canvas.height=txtH*oversample;text_canvas.dir=leftToRight;text_ctx.scale(oversample,oversample);text_ctx.fillStyle='rgba(0,0,0,0)';text_ctx.fillRect(0,0,text_ctx.canvas.width,text_ctx.canvas.height);text_ctx.fillStyle='white';text_ctx.textBaseline=baseLine;text_ctx.font=font_style+" "+textHeight+"px "+font_family;text_ctx.textAlign=textAlignment;for(i=0;i1){x3dom.debug.logError("X3D element has more than one Scene child (has "+ x3dElem.childNodes.length+").");} else{return sceneElems[0];} return null;};x3dom.X3DDocument.prototype._setup=function(sceneDoc,uriDocs,sceneElemPos){var doc=this;function cleanNodeBag(bag,node){for(var i=0,n=bag.length;i0){this._viewarea.animateTo(this._viewarea.getLightMatrix()[0],this._scene.getViewpoint());} break;case 117:this._viewarea.uprightView();break;case 118:var that=this;(function(){var viewpoint=that._viewarea._scene.getViewpoint();var mat_view=that._viewarea.getViewMatrix().inverse();var rotation=new x3dom.fields.Quaternion(0,0,1,0);rotation.setValue(mat_view);var rot=rotation.toAxisAngle();var translation=mat_view.e3();var center=viewpoint.getCenterOfRotation();x3dom.debug.logInfo('\n<Viewpoint position="'+translation.x.toFixed(5)+' ' +translation.y.toFixed(5)+' '+translation.z.toFixed(5)+'" '+'orientation="'+rot[0].x.toFixed(5)+' '+rot[0].y.toFixed(5)+' ' +rot[0].z.toFixed(5)+' '+rot[1].toFixed(5)+'" \n\t'+'zNear="'+viewpoint.getNear().toFixed(5)+'" '+'zFar="'+viewpoint.getFar().toFixed(5)+'" '+'centerOfRotation="'+center.x.toFixed(5)+' '+center.y.toFixed(5)+' '+center.z.toFixed(5)+'" '+'fieldOfView="'+viewpoint.getFieldOfView().toFixed(5)+'" '+'description="'+viewpoint._vf.description+'">'+'</Viewpoint>');})();break;case 119:nav.setType("walk",this._viewarea);break;case 121:nav.setType("freefly",this._viewarea);break;default:}};x3dom.X3DDocument.prototype.shutdown=function(ctx) {if(!ctx){return;} ctx.shutdown(this._viewarea);};x3dom.X3DDocument.prototype.hasAnimationStateChanged=function(){if(!this._viewarea){return false;} return this._viewarea.hasAnimationStateChanged();};x3dom.X3DDocument.prototype.isAnimating=function(){if(!this._viewarea){return false;} return this._viewarea.isAnimating();};x3dom.X3DDocument.prototype.incrementDownloads=function() {this.downloadCount++;} x3dom.X3DDocument.prototype.decrementDownloads=function() {this.downloadCount--;} x3dom.MatrixMixer=function(beginTime,endTime){this.beginTime=beginTime||0;this.endTime=endTime||1;this.isMixing=false;this._beginMat=x3dom.fields.SFMatrix4f.identity();this._beginInvMat=x3dom.fields.SFMatrix4f.identity();this._beginLogMat=x3dom.fields.SFMatrix4f.identity();this._endMat=x3dom.fields.SFMatrix4f.identity();this._endLogMat=x3dom.fields.SFMatrix4f.identity();this._beginRot=new x3dom.fields.Quaternion();this._endRot=new x3dom.fields.Quaternion();this._beginPos=new x3dom.fields.SFVec3f();this._endPos=new x3dom.fields.SFVec3f();this._result=x3dom.fields.SFMatrix4f.identity();this._useQuaternion=false;};x3dom.MatrixMixer.prototype._calcFraction=function(time){var fraction=(time-this.beginTime)/(this.endTime-this.beginTime);return(Math.sin((fraction*Math.PI)-(Math.PI/2))+1)/2.0;};x3dom.MatrixMixer.prototype._isValid=function(){var angles=this._beginMat.inverse().mult(this._endMat).getEulerAngles();return(Math.abs(angles[0])!=Math.PI&&Math.abs(angles[1])!=Math.PI&&Math.abs(angles[2])!=Math.PI);};x3dom.MatrixMixer.prototype._prepareQuaternionAnimation=function(){this._beginRot.setValue(this._beginMat);this._endRot.setValue(this._endMat);this._beginPos=this._beginMat.e3();this._endPos=this._endMat.e3();this._useQuaternion=true;};x3dom.MatrixMixer.prototype.reset=function(){this.beginTime=0;this.endTime=0;this._useQuaternion=false;this.isMixing=false;};x3dom.MatrixMixer.prototype.isActive=function(){return(this.beginTime>0);};x3dom.MatrixMixer.prototype.setBeginMatrix=function(mat){this._beginMat.setValues(mat);this._beginInvMat=mat.inverse();this._beginLogMat=x3dom.fields.SFMatrix4f.zeroMatrix();};x3dom.MatrixMixer.prototype.getBeginMatrix=function(mat){return this._beginMat;};x3dom.MatrixMixer.prototype.setEndMatrix=function(mat){this._endMat.setValues(mat);if(!this._isValid()){this._prepareQuaternionAnimation();} this._endLogMat=this._endMat.mult(this._beginInvMat).log();this._logDiffMat=this._endLogMat.addScaled(this._beginLogMat,-1);};x3dom.MatrixMixer.prototype.getEndMatrix=function(mat){return this._endMat;};x3dom.MatrixMixer.prototype._mixQuaternion=function(fraction){var rotation=this._beginRot.slerp(this._endRot,fraction);var translation=this._beginPos.addScaled(this._endPos.subtract(this._beginPos),fraction);this._result.setRotate(rotation);this._result.setTranslate(translation);return this._result.copy();};x3dom.MatrixMixer.prototype._mixMatrix=function(fraction){return this._logDiffMat.multiply(fraction).add(this._beginLogMat).exp().mult(this._beginMat);};x3dom.MatrixMixer.prototype.mix=function(time){if(time<=this.beginTime){return this._beginMat;}else if(time>=this.endTime){this.reset();return this._endMat;}else{this.isMixing=true;var fraction=this._calcFraction(time);if(this._useQuaternion){return this._mixQuaternion(fraction);}else{return this._mixMatrix(fraction);}}};x3dom.InputTypes={NAVIGATION:1,INTERACTION:2};x3dom.Viewarea=function(document,scene){this._doc=document;this._scene=scene;document._nodeBag.viewarea.push(this);this._pickingInfo={pickPos:new x3dom.fields.SFVec3f(0,0,0),pickNorm:new x3dom.fields.SFVec3f(0,0,1),pickObj:null,firstObj:null,lastObj:null,lastClickObj:null,shadowObjectId:-1};this._currentInputType=x3dom.InputTypes.NAVIGATION;this._rotMat=x3dom.fields.SFMatrix4f.identity();this._transMat=x3dom.fields.SFMatrix4f.identity();this._movement=new x3dom.fields.SFVec3f(0,0,0);this._needNavigationMatrixUpdate=true;this._deltaT=0;this._flyMat=null;this._pitch=0;this._yaw=0;this._eyePos=new x3dom.fields.SFVec3f(0,0,0);this._width=400;this._height=300;this._dx=0;this._dy=0;this._lastX=-1;this._lastY=-1;this._pressX=-1;this._pressY=-1;this._lastButton=0;this._points=0;this._numRenderedNodes=0;this._pick=new x3dom.fields.SFVec3f(0,0,0);this._pickNorm=new x3dom.fields.SFVec3f(0,0,1);this._isAnimating=false;this._isMoving=false;this._lastTS=0;this._mixer=new x3dom.MatrixMixer();this._interpolator=new x3dom.FieldInterpolator();this._animationStateChanged=false;this.vrFrameData=null;this.gamepads=null;this.vrLeftViewMatrix=new x3dom.fields.SFMatrix4f();this.vrRightViewMatrix=new x3dom.fields.SFMatrix4f();this.vrLeftProjMatrix=new x3dom.fields.SFMatrix4f();this.vrRightProjMatrix=new x3dom.fields.SFMatrix4f();this.vrControllerManager=new x3dom.VRControllerManager();this._inverseDevicePixelRatio=1.0/window.devicePixelRatio;this.arc=null;};x3dom.Viewarea.prototype.setVRFrameData=function(vrFrameData) {this.vrFrameData=vrFrameData;if(this.vrFrameData) {this.vrLeftViewMatrix.setFromArray(this.vrFrameData.leftViewMatrix),this.vrRightViewMatrix.setFromArray(this.vrFrameData.rightViewMatrix)}};x3dom.Viewarea.prototype.updateGamepads=function(vrDisplay) {this.vrControllerManager.update(this,vrDisplay);};x3dom.Viewarea.prototype.tick=function(timeStamp){var needMixAnim=false;var env=this._scene.getEnvironment();if(env._vf.enableARC&&this.arc==null){this.arc=new x3dom.arc.AdaptiveRenderControl(this._scene);} if(this._mixer.isActive()){var mat=this._mixer.mix(timeStamp);this._scene.getViewpoint().setView(mat);} if(this._interpolator.isActive()){var value=this._interpolator.interpolate(timeStamp);this._scene.getViewpoint().setZoom(value);} var needNavAnim=this.navigateTo(timeStamp);var lastIsAnimating=this._isAnimating;this._lastTS=timeStamp;this._isAnimating=(this._mixer.isMixing||this._interpolator.isInterpolating||needNavAnim);if(this._isAnimating!=lastIsAnimating){this._animationStateChanged=true;}else{this._animationStateChanged=false;} if(this.arc!=null){this.arc.update(this.isMovingOrAnimating()?1:0,this._doc._x3dElem.runtime.getFPS());} return(this._isAnimating||lastIsAnimating);};x3dom.Viewarea.prototype.isMoving=function(){return this._isMoving;};x3dom.Viewarea.prototype.isAnimating=function(){return this._isAnimating;};x3dom.Viewarea.prototype.hasAnimationStateChanged=function(){return this._animationStateChanged;};x3dom.Viewarea.prototype.isMovingOrAnimating=function(){return(this._isMoving||this._isAnimating);};x3dom.Viewarea.prototype.navigateTo=function(timeStamp){var navi=this._scene.getNavigationInfo();return navi._impl.navigateTo(this,timeStamp);};x3dom.Viewarea.prototype.moveFwd=function(){var navi=this._scene.getNavigationInfo();navi._impl.moveForward(this);};x3dom.Viewarea.prototype.moveBwd=function(){var navi=this._scene.getNavigationInfo();navi._impl.moveBackwards(this);};x3dom.Viewarea.prototype.strafeRight=function(){var navi=this._scene.getNavigationInfo();navi._impl.strafeRight(this);};x3dom.Viewarea.prototype.strafeLeft=function(){var navi=this._scene.getNavigationInfo();navi._impl.strafeLeft(this);};x3dom.Viewarea.prototype.animateTo=function(target,prev,dur){var navi=this._scene.getNavigationInfo();navi._impl.animateTo(this,target,prev,dur);};x3dom.Viewarea.prototype.orthoAnimateTo=function(target,prev,duration){var navi=this._scene.getNavigationInfo();navi._impl.orthoAnimateTo(this,target,prev,duration);};x3dom.Viewarea.prototype.zoom=function(zoomAmount){var navi=this._scene.getNavigationInfo();navi._impl.zoom(this,zoomAmount);};x3dom.Viewarea.prototype.getLights=function(){var enabledLights=[];for(var i=0;i0.0){return true;}} return false;};x3dom.Viewarea.prototype.hasPhysicalEnvironmentLight=function(){var light;for(var i=0;i0){var vol=this._scene.getVolume();if(vol.isValid()){var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();vol.getBounds(min,max);var l_arr=[];var viewpoint=this._scene.getViewpoint();var fov=viewpoint.getFieldOfView();var dia=max.subtract(min);var dist1=(dia.y/2.0)/Math.tan(fov/2.0)+(dia.z/2.0);var dist2=(dia.x/2.0)/Math.tan(fov/2.0)+(dia.z/2.0);dia=min.add(dia.multiply(0.5));for(i=0;idist2?dist1:dist2)));} l_arr[i]=lights[i].getViewMatrix(dia);} return l_arr;}} return[this.getViewMatrix()];};x3dom.Viewarea.prototype.getWCtoLCMatrix=function(lMat){var proj=this.getProjectionMatrix();var view;if(arguments.length===0){view=this.getLightMatrix()[0];}else{view=lMat;} return proj.mult(view);};x3dom.Viewarea.prototype.getWCtoLCMatricesPointLight=function(view,lightNode,mat_proj){var zNear=lightNode._vf.zNear;var zFar=lightNode._vf.zFar;var proj=this.getLightProjectionMatrix(view,zNear,zFar,false,mat_proj);proj._00=1;proj._11=1;var matrices=[];matrices[0]=proj.mult(view);var rotationMatrix;for(var i=1;i<=3;i++){rotationMatrix=x3dom.fields.SFMatrix4f.rotationY(i*Math.PI/2);matrices[i]=proj.mult(rotationMatrix.mult(view));} rotationMatrix=x3dom.fields.SFMatrix4f.rotationX(Math.PI/2);matrices[4]=proj.mult(rotationMatrix.mult(view));rotationMatrix=x3dom.fields.SFMatrix4f.rotationX(3*Math.PI/2);matrices[5]=proj.mult(rotationMatrix.mult(view));return matrices;};x3dom.Viewarea.prototype.getWCtoLCMatricesCascaded=function(view,lightNode,mat_proj){var numCascades=Math.max(1,Math.min(lightNode._vf.shadowCascades,6));var splitFactor=Math.max(0,Math.min(lightNode._vf.shadowSplitFactor,1));var splitOffset=Math.max(0,Math.min(lightNode._vf.shadowSplitOffset,1));var isSpotLight=x3dom.isa(lightNode,x3dom.nodeTypes.SpotLight);var zNear=lightNode._vf.zNear;var zFar=lightNode._vf.zFar;var proj=this.getLightProjectionMatrix(view,zNear,zFar,true,mat_proj);if(isSpotLight){proj._00=1;proj._11=1;} var viewProj=proj.mult(view);var matrices=[];if(numCascades==1){matrices[0]=viewProj;return matrices;} var cascadeSplits=this.getShadowSplitDepths(numCascades,splitFactor,splitOffset,true,mat_proj);for(var i=0;i0||zFar>0){var lightPos=lMat.inverse().e3();var nearScale=0.8;var farScale=1.2;var min=x3dom.fields.SFVec3f.copy(this._scene._lastMin);var max=x3dom.fields.SFVec3f.copy(this._scene._lastMax);var dia=max.subtract(min);var sRad=dia.length()/2;var sCenter=min.add(dia.multiply(0.5));var vDist=(lightPos.subtract(sCenter)).length();var near,far;if(sRad){if(vDist>sRad) near=(vDist-sRad)*nearScale;else near=1;far=(vDist+sRad)*farScale;} if(zNear>0)near=zNear;if(zFar>0)far=zFar;proj._22=-(far+near)/(far-near);proj._23=-2.0*far*near/(far-near);return proj;}else{var cropMatrix=this.getLightCropMatrix(proj.mult(lMat));return cropMatrix.mult(proj);}};x3dom.Viewarea.prototype.getProjectionMatrix=function(){if(this.vrFrameData){return this.vrLeftProjMatrix.setFromArray(this.vrFrameData.leftProjectionMatrix);}else{var viewpoint=this._scene.getViewpoint();return viewpoint.getProjectionMatrix(this._width/this._height);}};x3dom.Viewarea.prototype.getProjectionMatrices=function() {if(this.vrFrameData) {return[this.vrLeftProjMatrix.setFromArray(this.vrFrameData.leftProjectionMatrix),this.vrRightProjMatrix.setFromArray(this.vrFrameData.rightProjectionMatrix)];} else {var viewpoint=this._scene.getViewpoint();var projectionMatrix=viewpoint.getProjectionMatrix(this._width/this._height);return[projectionMatrix,projectionMatrix]}};x3dom.Viewarea.prototype.getViewfrustum=function(clipMat){var env=this._scene.getEnvironment();if(env._vf.frustumCulling==true){if(arguments.length==0){var proj=this.getProjectionMatrix();var view=this.getViewMatrix();return new x3dom.fields.FrustumVolume(proj.mult(view));}else{return new x3dom.fields.FrustumVolume(clipMat);}} return null;};x3dom.Viewarea.prototype.getWCtoCCMatrix=function(){var view=this.getViewMatrix();var proj=this.getProjectionMatrix();return proj.mult(view);};x3dom.Viewarea.prototype.getCCtoWCMatrix=function(){var mat=this.getWCtoCCMatrix();return mat.inverse();};x3dom.Viewarea.prototype.calcViewRay=function(x,y,mat){var cctowc=mat?mat:this.getCCtoWCMatrix();var rx=x/(this._width-1.0)*2.0-1.0;var ry=(this._height-1.0-y)/(this._height-1.0)*2.0-1.0;var from=cctowc.multFullMatrixPnt(new x3dom.fields.SFVec3f(rx,ry,-1));var at=cctowc.multFullMatrixPnt(new x3dom.fields.SFVec3f(rx,ry,1));var dir=at.subtract(from);return new x3dom.fields.Ray(from,dir);};x3dom.Viewarea.prototype.showAll=function(axis,updateCenterOfRotation){if(axis===undefined) axis="negZ";if(updateCenterOfRotation===undefined){updateCenterOfRotation=false;} var scene=this._scene;scene.updateVolume();var min=x3dom.fields.SFVec3f.copy(scene._lastMin);var max=x3dom.fields.SFVec3f.copy(scene._lastMax);var x="x",y="y",z="z";var sign=1;var to,from=new x3dom.fields.SFVec3f(0,0,-1);switch(axis){case"posX":sign=-1;case"negX":z="x";x="y";y="z";to=new x3dom.fields.SFVec3f(sign,0,0);break;case"posY":sign=-1;case"negY":z="y";x="z";y="x";to=new x3dom.fields.SFVec3f(0,sign,0);break;case"posZ":sign=-1;case"negZ":default:to=new x3dom.fields.SFVec3f(0,0,-sign);break;} var viewpoint=scene.getViewpoint();var fov=viewpoint.getFieldOfView();var isOrtho=x3dom.isa(viewpoint,x3dom.nodeTypes.OrthoViewpoint);var dia=max.subtract(min);var dia2=dia.multiply(0.5);var center=min.add(dia2);if(updateCenterOfRotation){viewpoint.setCenterOfRotation(center);} var aspect=Math.min(this._width/this._height,1);var diaz2=dia[z]/2.0,tanfov2=Math.tan(fov/2.0);var dist1=(dia[y]/2.0)/tanfov2+diaz2;var dist2=(dia[x]/2.0)/tanfov2+diaz2;dia=min.add(dia.multiply(0.5));if(isOrtho){dia[z]+=sign*(dist1>dist2?dist1:dist2)*3.01;}else{dia[z]+=sign*(dist1>dist2?dist1:dist2)*1.01;} dia[z]/=aspect;var quat=x3dom.fields.Quaternion.rotateFromTo(from,to);var viewmat=quat.toMatrix();viewmat=viewmat.mult(x3dom.fields.SFMatrix4f.translation(dia.negate()));if(isOrtho){this.orthoAnimateTo(dist1,Math.abs(viewpoint._fieldOfView[0]));this.animateTo(viewmat,viewpoint);}else{this.animateTo(viewmat,viewpoint);}};x3dom.Viewarea.prototype.fit=function(min,max,updateCenterOfRotation){if(updateCenterOfRotation===undefined){updateCenterOfRotation=true;} var dia2=max.subtract(min).multiply(0.5);var center=min.add(dia2);var bsr=dia2.length();var viewpoint=this._scene.getViewpoint();var fov=viewpoint.getFieldOfView();var viewmat=x3dom.fields.SFMatrix4f.copy(this.getViewMatrix());var rightDir=new x3dom.fields.SFVec3f(viewmat._00,viewmat._01,viewmat._02);var upDir=new x3dom.fields.SFVec3f(viewmat._10,viewmat._11,viewmat._12);var viewDir=new x3dom.fields.SFVec3f(viewmat._20,viewmat._21,viewmat._22);var aspect=Math.min(this._width/this._height,1);var tanfov2=Math.tan(fov/2.0);var dist=bsr/tanfov2/aspect;var eyePos=center.add(viewDir.multiply(dist));viewmat._03=-rightDir.dot(eyePos);viewmat._13=-upDir.dot(eyePos);viewmat._23=-viewDir.dot(eyePos);if(updateCenterOfRotation){viewpoint.setCenterOfRotation(center);} if(x3dom.isa(viewpoint,x3dom.nodeTypes.OrthoViewpoint)){this.orthoAnimateTo(dist/2.01,Math.abs(viewpoint._fieldOfView[0]));this.animateTo(viewmat,viewpoint);}else{this.animateTo(viewmat,viewpoint);}};x3dom.Viewarea.prototype.resetView=function(){var navi=this._scene.getNavigationInfo();navi._impl.resetView(this);};x3dom.Viewarea.prototype.resetNavHelpers=function(){this._rotMat=x3dom.fields.SFMatrix4f.identity();this._transMat=x3dom.fields.SFMatrix4f.identity();this._movement=new x3dom.fields.SFVec3f(0,0,0);this._needNavigationMatrixUpdate=true;};x3dom.Viewarea.prototype.uprightView=function(){var mat=this.getViewMatrix().inverse();var from=mat.e3();var at=from.subtract(mat.e2());var up=new x3dom.fields.SFVec3f(0,1,0);var s=mat.e2().cross(up).normalize();var v=s.cross(up).normalize();at=from.add(v);mat=x3dom.fields.SFMatrix4f.lookAt(from,at,up);mat=mat.inverse();this.animateTo(mat,this._scene.getViewpoint());};x3dom.Viewarea.prototype.callEvtHandler=function(node,eventType,event){if(!node||!node._xmlNode) return null;try{var attrib=node._xmlNode[eventType];if(typeof(attrib)==="function"){attrib.call(node._xmlNode,event);}else{var funcStr=node._xmlNode.getAttribute(eventType);var func=new Function('event',funcStr);func.call(node._xmlNode,event);} var list=node._listeners[event.type];if(list){for(var it=0;it0&&func!==undefined){for(i=0;i=0)&&navType==="lookat"&&this._pressX===x&&this._pressY===y){var step=(this._lastButton&2)?-1:1;var dist=this._pickingInfo.pickPos.subtract(this._from).length()/tDist;var laMat=new x3dom.fields.SFMatrix4f();laMat.setValues(this.getViewMatrix());laMat=laMat.inverse();var from=laMat.e3();var at=from.subtract(laMat.e2());var up=laMat.e1();dir=this._pickingInfo.pickPos.subtract(from);var len=dir.length();dir=dir.normalize();var newAt=from.addScaled(dir,len);var s=dir.cross(up).normalize();dir=s.cross(up).normalize();if(step<0){dist=(0.5+len+dist)*2;} var newFrom=newAt.addScaled(dir,dist);laMat=x3dom.fields.SFMatrix4f.lookAt(newFrom,newAt,up);laMat=laMat.inverse();dist=newFrom.subtract(from).length();var dur=Math.max(0.5,Math.log((1+dist)/navi._vf.speed));this.animateTo(laMat,this._scene.getViewpoint(),dur);} this._dx=0;this._dy=0;this._lastX=x;this._lastY=y;this._lastButton=buttonState;this._isMoving=false;};x3dom.Viewarea.prototype.onMouseOver=function(x,y,buttonState){this._dx=0;this._dy=0;this._lastButton=0;this._isMoving=false;this._lastX=x;this._lastY=y;this._deltaT=0;};x3dom.Viewarea.prototype.onMouseOut=function(x,y,buttonState){this._dx=0;this._dy=0;this._lastButton=0;this._isMoving=false;this._lastX=x;this._lastY=y;this._deltaT=0;var i;var affectedPointingSensorsList=this._doc._nodeBag.affectedPointingSensors;for(i=0;i0){this._currentInputType=x3dom.InputTypes.INTERACTION;}else{this._currentInputType=x3dom.InputTypes.NAVIGATION;}};x3dom.Viewarea.prototype.getRenderMode=function(){return this._points;};x3dom.Viewarea.prototype.getShadowedLights=function(){var shadowedLights=[];var shadowIndex=0;var slights=this.getLights();for(var i=0;i0.0){shadowedLights[shadowIndex]=slights[i];shadowIndex++;}} return shadowedLights;};x3dom.Viewarea.prototype.getShadowSplitDepths=function(numCascades,splitFactor,splitOffset,postProject,mat_proj){var logSplit;var practSplit=[];var viewPoint=this._scene.getViewpoint();var zNear=viewPoint.getNear();var zFar=viewPoint.getFar();practSplit[0]=zNear;zNear=zNear+splitOffset*(zFar-zNear)/10;for(var i=1;i1.0||xMax<-1.0){xMin=-1.0;xMax=1.0;}else{xMin=Math.max(xMin,-1.0);xMax=Math.min(xMax,1.0);} if(yMin>1.0||yMax<-1.0){yMin=-1.0;yMax=1.0;}else{yMin=Math.max(yMin,-1.0);yMax=Math.min(yMax,1.0);} if(zMin>1.0||zMax<-1.0){zMin=-1.0;zMax=1.0;}else{zMin=Math.max(zMin,-1.0);zMax=Math.min(zMax,1.0);} var minValues=new x3dom.fields.SFVec3f(xMin,yMin,zMin);var maxValues=new x3dom.fields.SFVec3f(xMax,yMax,zMax);return new x3dom.fields.BoxVolume(minValues,maxValues);} var frustumBB=clip(minFrustum,maxFrustum);var scaleX=2.0/(frustumBB.max.x-frustumBB.min.x);var scaleY=2.0/(frustumBB.max.y-frustumBB.min.y);var offsetX=-(scaleX*(frustumBB.max.x+frustumBB.min.x))/2.0;var offsetY=-(scaleY*(frustumBB.max.y+frustumBB.min.y))/2.0;var fittingMatrix=x3dom.fields.SFMatrix4f.identity();fittingMatrix._00=scaleX;fittingMatrix._11=scaleY;fittingMatrix._03=offsetX;fittingMatrix._13=offsetY;return fittingMatrix;};x3dom.Mesh=function(parent){this._parent=parent;this._vol=new x3dom.fields.BoxVolume();this._invalidate=true;this._numFaces=0;this._numCoords=0;this._primType='TRIANGLES';this._positions=[];this._normals=[];this._texCoords=[];this._texCoords2=[];this._colors=[];this._indices=[];this._tangents=[];this._binormals=[];this._positions[0]=[];this._normals[0]=[];this._texCoords[0]=[];this._texCoords2[0]=[];this._colors[0]=[];this._indices[0]=[];this._tangents[0]=[];this._binormals[0]=[];};x3dom.Mesh.prototype._dynamicFields={};x3dom.Mesh.prototype._numPosComponents=3;x3dom.Mesh.prototype._numTexComponents=2;x3dom.Mesh.prototype._numTex2Components=2;x3dom.Mesh.prototype._numColComponents=3;x3dom.Mesh.prototype._numNormComponents=3;x3dom.Mesh.prototype._numTangentComponents=3;x3dom.Mesh.prototype._numBinormalComponents=3;x3dom.Mesh.prototype._lit=true;x3dom.Mesh.prototype._vol=null;x3dom.Mesh.prototype._invalidate=true;x3dom.Mesh.prototype._numFaces=0;x3dom.Mesh.prototype._numCoords=0;x3dom.Mesh.prototype.getVolume=function(){if(this._invalidate==true&&!this._vol.isValid()){var coords=this._positions[0];var n=coords.length;if(n>=3){var initVal=new x3dom.fields.SFVec3f(coords[0],coords[1],coords[2]);this._vol.setBounds(initVal,initVal);for(var i=3;icoords[i]){this._vol.min.x=coords[i];} if(this._vol.min.y>coords[i+1]){this._vol.min.y=coords[i+1];} if(this._vol.min.z>coords[i+2]){this._vol.min.z=coords[i+2];} if(this._vol.max.xm)?this._posSize/3:m/3;num=3*((num-Math.floor(num)>0)?Math.floor(num+1):num);for(i=0;ix3dom.fields.Eps){for(i=0;i=0);if(k){this._indices[i]=indices.slice(i*MAX,(i+1)*MAX);}else{this._indices[i]=indices.slice(i*MAX);} if(!isMultiInd){if(i){var m=i*MAX;for(var j=0,l=this._indices[i].length;j++i*MAX*3);};x3dom.Mesh.prototype.calcTexCoords=function(mode){this._texCoords[0]=[];if(mode.toLowerCase()==="sphere-local"){for(var i=0,j=0,n=this._normals[0].length;i=dia.y){if(dia.x>=dia.z){S=0;T=dia.y>=dia.z?1:2;}else{S=2;T=0;}}else{if(dia.y>=dia.z){S=1;T=dia.x>=dia.z?0:2;}else{S=2;T=1;}} var sDenom=1,tDenom=1;var sMin=0,tMin=0;switch(S){case 0:sDenom=dia.x;sMin=min.x;break;case 1:sDenom=dia.y;sMin=min.y;break;case 2:sDenom=dia.z;sMin=min.z;break;} switch(T){case 0:tDenom=dia.x;tMin=min.x;break;case 1:tDenom=dia.y;tMin=min.y;break;case 2:tDenom=dia.z;tMin=min.z;break;} for(var k=0,l=0,m=this._positions[0].length;k=16){if(!needTranspose){return new x3dom.fields.SFMatrix4f(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7],arr[8],arr[9],arr[10],arr[11],arr[12],arr[13],arr[14],arr[15]);}else{return new x3dom.fields.SFMatrix4f(arr[0],arr[4],arr[8],arr[12],arr[1],arr[5],arr[9],arr[13],arr[2],arr[6],arr[10],arr[14],arr[3],arr[7],arr[11],arr[15]);}}else if(arr.length===6){return new x3dom.fields.SFMatrix4f(arr[0],arr[1],0,arr[4],arr[2],arr[3],0,arr[5],0,0,1,0,0,0,0,1);}else{x3dom.debug.logWarning("SFMatrix4f - can't parse string: "+str);return x3dom.fields.SFMatrix4f.identity();}};x3dom.fields.SFMatrix4f.prototype.mult=function(that){return new x3dom.fields.SFMatrix4f(this._00*that._00+this._01*that._10+this._02*that._20+this._03*that._30,this._00*that._01+this._01*that._11+this._02*that._21+this._03*that._31,this._00*that._02+this._01*that._12+this._02*that._22+this._03*that._32,this._00*that._03+this._01*that._13+this._02*that._23+this._03*that._33,this._10*that._00+this._11*that._10+this._12*that._20+this._13*that._30,this._10*that._01+this._11*that._11+this._12*that._21+this._13*that._31,this._10*that._02+this._11*that._12+this._12*that._22+this._13*that._32,this._10*that._03+this._11*that._13+this._12*that._23+this._13*that._33,this._20*that._00+this._21*that._10+this._22*that._20+this._23*that._30,this._20*that._01+this._21*that._11+this._22*that._21+this._23*that._31,this._20*that._02+this._21*that._12+this._22*that._22+this._23*that._32,this._20*that._03+this._21*that._13+this._22*that._23+this._23*that._33,this._30*that._00+this._31*that._10+this._32*that._20+this._33*that._30,this._30*that._01+this._31*that._11+this._32*that._21+this._33*that._31,this._30*that._02+this._31*that._12+this._32*that._22+this._33*that._32,this._30*that._03+this._31*that._13+this._32*that._23+this._33*that._33);};x3dom.fields.SFMatrix4f.prototype.multMatrixPnt=function(vec){return new x3dom.fields.SFVec3f(this._00*vec.x+this._01*vec.y+this._02*vec.z+this._03,this._10*vec.x+this._11*vec.y+this._12*vec.z+this._13,this._20*vec.x+this._21*vec.y+this._22*vec.z+this._23);};x3dom.fields.SFMatrix4f.prototype.multMatrixVec=function(vec){return new x3dom.fields.SFVec3f(this._00*vec.x+this._01*vec.y+this._02*vec.z,this._10*vec.x+this._11*vec.y+this._12*vec.z,this._20*vec.x+this._21*vec.y+this._22*vec.z);};x3dom.fields.SFMatrix4f.prototype.multFullMatrixPnt=function(vec){var w=this._30*vec.x+this._31*vec.y+this._32*vec.z+this._33;if(w){w=1.0/w;} return new x3dom.fields.SFVec3f((this._00*vec.x+this._01*vec.y+this._02*vec.z+this._03)*w,(this._10*vec.x+this._11*vec.y+this._12*vec.z+this._13)*w,(this._20*vec.x+this._21*vec.y+this._22*vec.z+this._23)*w);};x3dom.fields.SFMatrix4f.prototype.multMatrixPlane=function(plane){var normal=new x3dom.fields.SFVec3f(plane.x,plane.y,plane.z);var memberPnt=normal.multiply(-plane.w);memberPnt=this.multMatrixPnt(memberPnt);var invTranspose=this.inverse().transpose();normal=invTranspose.multMatrixVec(normal);var d=-normal.dot(memberPnt);return new x3dom.fields.SFVec4f(normal.x,normal.y,normal.z,d);};x3dom.fields.SFMatrix4f.prototype.transpose=function(){return new x3dom.fields.SFMatrix4f(this._00,this._10,this._20,this._30,this._01,this._11,this._21,this._31,this._02,this._12,this._22,this._32,this._03,this._13,this._23,this._33);};x3dom.fields.SFMatrix4f.prototype.negate=function(){return new x3dom.fields.SFMatrix4f(-this._00,-this._01,-this._02,-this._03,-this._10,-this._11,-this._12,-this._13,-this._20,-this._21,-this._22,-this._23,-this._30,-this._31,-this._32,-this._33);};x3dom.fields.SFMatrix4f.prototype.multiply=function(s){return new x3dom.fields.SFMatrix4f(s*this._00,s*this._01,s*this._02,s*this._03,s*this._10,s*this._11,s*this._12,s*this._13,s*this._20,s*this._21,s*this._22,s*this._23,s*this._30,s*this._31,s*this._32,s*this._33);};x3dom.fields.SFMatrix4f.prototype.add=function(that){return new x3dom.fields.SFMatrix4f(this._00+that._00,this._01+that._01,this._02+that._02,this._03+that._03,this._10+that._10,this._11+that._11,this._12+that._12,this._13+that._13,this._20+that._20,this._21+that._21,this._22+that._22,this._23+that._23,this._30+that._30,this._31+that._31,this._32+that._32,this._33+that._33);};x3dom.fields.SFMatrix4f.prototype.addScaled=function(that,s){return new x3dom.fields.SFMatrix4f(this._00+s*that._00,this._01+s*that._01,this._02+s*that._02,this._03+s*that._03,this._10+s*that._10,this._11+s*that._11,this._12+s*that._12,this._13+s*that._13,this._20+s*that._20,this._21+s*that._21,this._22+s*that._22,this._23+s*that._23,this._30+s*that._30,this._31+s*that._31,this._32+s*that._32,this._33+s*that._33);};x3dom.fields.SFMatrix4f.prototype.setValues=function(that){this._00=that._00;this._01=that._01;this._02=that._02;this._03=that._03;this._10=that._10;this._11=that._11;this._12=that._12;this._13=that._13;this._20=that._20;this._21=that._21;this._22=that._22;this._23=that._23;this._30=that._30;this._31=that._31;this._32=that._32;this._33=that._33;};x3dom.fields.SFMatrix4f.prototype.setValue=function(v1,v2,v3,v4){this._00=v1.x;this._01=v2.x;this._02=v3.x;this._10=v1.y;this._11=v2.y;this._12=v3.y;this._20=v1.z;this._21=v2.z;this._22=v3.z;this._30=0;this._31=0;this._32=0;if(arguments.length>3){this._03=v4.x;this._13=v4.y;this._23=v4.z;this._33=1;}};x3dom.fields.SFMatrix4f.prototype.setFromArray=function(a){this._00=a[0];this._01=a[4];this._02=a[8];this._03=a[12];this._10=a[1];this._11=a[5];this._12=a[9];this._13=a[13];this._20=a[2];this._21=a[6];this._22=a[10];this._23=a[14];this._30=a[3];this._31=a[7];this._32=a[11];this._33=a[15];return this;};x3dom.fields.SFMatrix4f.fromArray=function(a){var m=new x3dom.fields.SFMatrix4f();m._00=a[0];m._01=a[4];m._02=a[8];m._03=a[12];m._10=a[1];m._11=a[5];m._12=a[9];m._13=a[13];m._20=a[2];m._21=a[6];m._22=a[10];m._23=a[14];m._30=a[3];m._31=a[7];m._32=a[11];m._33=a[15];return m;};x3dom.fields.SFMatrix4f.prototype.fromRotationTranslationScale=function(rotation,translation,scale){translation=translation||new x3dom.fields.SFVec3f();rotation=rotation||new x3dom.fields.Quaternion();scale=scale||new x3dom.fields.SFVec3f(1,1,1);var x=rotation.x,y=rotation.y,z=rotation.z,w=rotation.w;var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;this._00=(1-(yy+zz))*scale.x;this._10=(xy+wz)*scale.x;this._20=(xz-wy)*scale.x;this._30=0;this._01=(xy-wz)*scale.y;this._11=(1-(xx+zz))*scale.y;this._21=(yz+wx)*scale.y;this._31=0;this._02=(xz+wy)*scale.z;this._12=(yz-wx)*scale.z;this._22=(1-(xx+yy))*scale.z;this._32=0;this._03=translation.x;this._13=translation.y;this._23=translation.z;this._33=1 return this;};x3dom.fields.SFMatrix4f.fromRotationTranslationScale=function(rotation,translation,scale){translation=translation||new x3dom.fields.SFVec3f();rotation=rotation||new x3dom.fields.Quaternion();scale=scale||new x3dom.fields.SFVec3f(1,1,1);var m=new x3dom.fields.SFMatrix4f();var x=rotation.x,y=rotation.y,z=rotation.z,w=rotation.w;var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;m._00=(1-(yy+zz))*scale.x;m._10=(xy+wz)*scale.x;m._20=(xz-wy)*scale.x;m._30=0;m._01=(xy-wz)*scale.y;m._11=(1-(xx+zz))*scale.y;m._21=(yz+wx)*scale.y;m._31=0;m._02=(xz+wy)*scale.z;m._12=(yz-wx)*scale.z;m._22=(1-(xx+yy))*scale.z;m._32=0;m._03=translation.x;m._13=translation.y;m._23=translation.z;m._33=1 return m;};x3dom.fields.SFMatrix4f.prototype.toGL=function(){return[this._00,this._10,this._20,this._30,this._01,this._11,this._21,this._31,this._02,this._12,this._22,this._32,this._03,this._13,this._23,this._33];};x3dom.fields.SFMatrix4f.fromGL=function(array){return[this._00,this._10,this._20,this._30,this._01,this._11,this._21,this._31,this._02,this._12,this._22,this._32,this._03,this._13,this._23,this._33];};x3dom.fields.SFMatrix4f.prototype.at=function(i,j){var field="_"+i+j;return this[field];};x3dom.fields.SFMatrix4f.prototype.sqrt=function(){var Y=x3dom.fields.SFMatrix4f.identity();var result=x3dom.fields.SFMatrix4f.copy(this);for(var i=0;i<6;i++){var iX=result.inverse();var iY=(i==0)?x3dom.fields.SFMatrix4f.identity():Y.inverse();var rd=result.det(),yd=Y.det();var g=Math.abs(Math.pow(rd*yd,-0.125));var ig=1.0/g;result=result.multiply(g);result=result.addScaled(iY,ig);result=result.multiply(0.5);Y=Y.multiply(g);Y=Y.addScaled(iX,ig);Y=Y.multiply(0.5);} return result;};x3dom.fields.SFMatrix4f.prototype.normInfinity=function(){var t=0,m=0;if((t=Math.abs(this._00))>m){m=t;} if((t=Math.abs(this._01))>m){m=t;} if((t=Math.abs(this._02))>m){m=t;} if((t=Math.abs(this._03))>m){m=t;} if((t=Math.abs(this._10))>m){m=t;} if((t=Math.abs(this._11))>m){m=t;} if((t=Math.abs(this._12))>m){m=t;} if((t=Math.abs(this._13))>m){m=t;} if((t=Math.abs(this._20))>m){m=t;} if((t=Math.abs(this._21))>m){m=t;} if((t=Math.abs(this._22))>m){m=t;} if((t=Math.abs(this._23))>m){m=t;} if((t=Math.abs(this._30))>m){m=t;} if((t=Math.abs(this._31))>m){m=t;} if((t=Math.abs(this._32))>m){m=t;} if((t=Math.abs(this._33))>m){m=t;} return m;};x3dom.fields.SFMatrix4f.prototype.norm1_3x3=function(){var max=Math.abs(this._00)+ Math.abs(this._10)+ Math.abs(this._20);var t=0;if((t=Math.abs(this._01)+ Math.abs(this._11)+ Math.abs(this._21))>max){max=t;} if((t=Math.abs(this._02)+ Math.abs(this._12)+ Math.abs(this._22))>max){max=t;} return max;};x3dom.fields.SFMatrix4f.prototype.normInf_3x3=function(){var max=Math.abs(this._00)+ Math.abs(this._01)+ Math.abs(this._02);var t=0;if((t=Math.abs(this._10)+ Math.abs(this._11)+ Math.abs(this._12))>max){max=t;} if((t=Math.abs(this._20)+ Math.abs(this._21)+ Math.abs(this._22))>max){max=t;} return max;};x3dom.fields.SFMatrix4f.prototype.adjointT_3x3=function(){var result=x3dom.fields.SFMatrix4f.identity();result._00=this._11*this._22-this._12*this._21;result._01=this._12*this._20-this._10*this._22;result._02=this._10*this._21-this._11*this._20;result._10=this._21*this._02-this._22*this._01;result._11=this._22*this._00-this._20*this._02;result._12=this._20*this._01-this._21*this._00;result._20=this._01*this._12-this._02*this._11;result._21=this._02*this._10-this._00*this._12;result._22=this._00*this._11-this._01*this._10;return result;};x3dom.fields.SFMatrix4f.prototype.equals=function(that){var eps=0.000000000001;return Math.abs(this._00-that._00)4){m=x3dom.fields.SFMatrix4f.translation(center.negate());m=m.mult(this);var c=x3dom.fields.SFMatrix4f.translation(center);m=m.mult(c);}else{m=x3dom.fields.SFMatrix4f.copy(this);} var flip=m.decompose(translation,rotation,scaleFactor,scaleOrientation);scaleFactor.setValues(scaleFactor.multiply(flip));};x3dom.fields.SFMatrix4f.prototype.decompose=function(t,r,s,so){var A=x3dom.fields.SFMatrix4f.copy(this);var Q=x3dom.fields.SFMatrix4f.identity(),S=x3dom.fields.SFMatrix4f.identity(),SO=x3dom.fields.SFMatrix4f.identity();t.x=A._03;t.y=A._13;t.z=A._23;A._03=0.0;A._13=0.0;A._23=0.0;A._30=0.0;A._31=0.0;A._32=0.0;var det=A.polarDecompose(Q,S);var f=1.0;if(det<0.0){Q=Q.negate();f=-1.0;} r.setValue(Q);S.spectralDecompose(SO,s);so.setValue(SO);return f;};x3dom.fields.SFMatrix4f.prototype.polarDecompose=function(Q,S){var TOL=0.000000000001;var Mk=this.transpose();var Ek=x3dom.fields.SFMatrix4f.identity();var Mk_one=Mk.norm1_3x3();var Mk_inf=Mk.normInf_3x3();var MkAdjT;var MkAdjT_one,MkAdjT_inf;var Ek_one,Mk_det;do{MkAdjT=Mk.adjointT_3x3();Mk_det=Mk._00*MkAdjT._00+ Mk._01*MkAdjT._01+ Mk._02*MkAdjT._02;if(Mk_det==0.0){x3dom.debug.logWarning("polarDecompose: Mk_det == 0.0");break;} MkAdjT_one=MkAdjT.norm1_3x3();MkAdjT_inf=MkAdjT.normInf_3x3();var gamma=Math.sqrt(Math.sqrt((MkAdjT_one*MkAdjT_inf)/(Mk_one*Mk_inf))/Math.abs(Mk_det));var g1=0.5*gamma;var g2=0.5/(gamma*Mk_det);Ek.setValues(Mk);Mk=Mk.multiply(g1);Mk=Mk.addScaled(MkAdjT,g2);Ek=Ek.addScaled(Mk,-1.0);Ek_one=Ek.norm1_3x3();Mk_one=Mk.norm1_3x3();Mk_inf=Mk.normInf_3x3();}while(Ek_one>(Mk_one*TOL));Q.setValues(Mk.transpose());S.setValues(Mk.mult(this));for(var i=0;i<3;++i){for(var j=i;j<3;++j){S['_'+j+i]=0.5*(S['_'+j+i]+S['_'+i+j]);S['_'+i+j]=0.5*(S['_'+j+i]+S['_'+i+j]);}} return Mk_det;};x3dom.fields.SFMatrix4f.prototype.spectralDecompose=function(SO,k){var next=[1,2,0];var maxIterations=20;var diag=[this._00,this._11,this._22];var offDiag=[this._12,this._20,this._01];for(var iter=0;iter=0;--i){var p=next[i];var q=next[p];var absOffDiag=Math.abs(offDiag[i]);var g=100.0*absOffDiag;if(absOffDiag>0.0){var t=0,h=diag[q]-diag[p];var absh=Math.abs(h);if(absh+g==absh){t=offDiag[i]/h;}else{var theta=0.5*h/offDiag[i];t=1.0/(Math.abs(theta)+Math.sqrt(theta*theta+1.0));t=theta<0.0?-t:t;} var c=1.0/Math.sqrt(t*t+1.0);var s=t*c;var tau=s/(c+1.0);var ta=t*offDiag[i];offDiag[i]=0.0;diag[p]-=ta;diag[q]+=ta;var offDiagq=offDiag[q];offDiag[q]-=s*(offDiag[p]+tau*offDiagq);offDiag[p]+=s*(offDiagq-tau*offDiag[p]);for(var j=2;j>=0;--j){var a=SO['_'+j+p];var b=SO['_'+j+q];SO['_'+j+p]-=s*(b+tau*a);SO['_'+j+q]+=s*(a-tau*b);}}}} k.x=diag[0];k.y=diag[1];k.z=diag[2];};x3dom.fields.SFMatrix4f.prototype.log=function(){var maxiter=12;var eps=1e-12;var A=x3dom.fields.SFMatrix4f.copy(this),Z=x3dom.fields.SFMatrix4f.copy(this);Z._00-=1;Z._11-=1;Z._22-=1;Z._33-=1;var k=0;while(Z.normInfinity()>0.5){A=A.sqrt();Z.setValues(A);Z._00-=1;Z._11-=1;Z._22-=1;Z._33-=1;k++;} A._00-=1;A._11-=1;A._22-=1;A._33-=1;A=A.negate();Z.setValues(A);var result=x3dom.fields.SFMatrix4f.copy(A);var i=1;while(Z.normInfinity()>eps&&i0.0001){theta_1=-Math.asin(this._20);theta_2=Math.PI-theta_1;cos_theta_1=Math.cos(theta_1);cos_theta_2=Math.cos(theta_2);psi_1=Math.atan2(this._21/cos_theta_1,this._22/cos_theta_1);psi_2=Math.atan2(this._21/cos_theta_2,this._22/cos_theta_2);phi_1=Math.atan2(this._10/cos_theta_1,this._00/cos_theta_1);phi_2=Math.atan2(this._10/cos_theta_2,this._00/cos_theta_2);return[psi_1,theta_1,phi_1,psi_2,theta_2,phi_2];}else{phi=0;if(this._20==-1.0){theta=Math.PI/2.0;psi=phi+Math.atan2(this._01,this._02);}else{theta=-(Math.PI/2.0);psi=-phi+Math.atan2(-this._01,-this._02);} return[psi,theta,phi,psi,theta,phi];}};x3dom.fields.SFMatrix4f.prototype.toString=function(){return this._00.toFixed(6)+' '+this._10.toFixed(6)+' '+ this._20.toFixed(6)+' '+this._30.toFixed(6)+' '+ this._01.toFixed(6)+' '+this._11.toFixed(6)+' '+ this._21.toFixed(6)+' '+this._31.toFixed(6)+' '+ this._02.toFixed(6)+' '+this._12.toFixed(6)+' '+ this._22.toFixed(6)+' '+this._32.toFixed(6)+' '+ this._03.toFixed(6)+' '+this._13.toFixed(6)+' '+ this._23.toFixed(6)+' '+this._33.toFixed(6);};x3dom.fields.SFMatrix4f.prototype.setValueByStr=function(str){var needTranspose=false;var val=/matrix.*\((.+)\)/;if(val.exec(str)){str=RegExp.$1;needTranspose=true;} var arr=Array.map(str.split(/[,\s]+/),function(n){return+n;});if(arr.length>=16){if(!needTranspose){this._00=arr[0];this._01=arr[1];this._02=arr[2];this._03=arr[3];this._10=arr[4];this._11=arr[5];this._12=arr[6];this._13=arr[7];this._20=arr[8];this._21=arr[9];this._22=arr[10];this._23=arr[11];this._30=arr[12];this._31=arr[13];this._32=arr[14];this._33=arr[15];}else{this._00=arr[0];this._01=arr[4];this._02=arr[8];this._03=arr[12];this._10=arr[1];this._11=arr[5];this._12=arr[9];this._13=arr[13];this._20=arr[2];this._21=arr[6];this._22=arr[10];this._23=arr[14];this._30=arr[3];this._31=arr[7];this._32=arr[11];this._33=arr[15];}}else if(arr.length===6){this._00=arr[0];this._01=arr[1];this._02=0;this._03=arr[4];this._10=arr[2];this._11=arr[3];this._12=0;this._13=arr[5];this._20=0;this._21=0;this._22=1;this._23=0;this._30=0;this._31=0;this._32=0;this._33=1;}else{x3dom.debug.logWarning("SFMatrix4f - can't parse string: "+str);} return this;};x3dom.fields.SFVec2f=function(x,y){if(arguments.length===0){this.x=0;this.y=0;}else{this.x=x;this.y=y;}};x3dom.fields.SFVec2f.copy=function(v){return new x3dom.fields.SFVec2f(v.x,v.y);};x3dom.fields.SFVec2f.parse=function(str){var m=/^\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*$/.exec(str);if(m===null)return new x3dom.fields.SFVec2f();return new x3dom.fields.SFVec2f(+m[1],+m[2]);};x3dom.fields.SFVec2f.prototype.copy=function(){return x3dom.fields.SFVec2f.copy(this);};x3dom.fields.SFVec2f.prototype.setValues=function(that){this.x=that.x;this.y=that.y;};x3dom.fields.SFVec2f.prototype.at=function(i){switch(i){case 0:return this.x;case 1:return this.y;default:return this.x;}};x3dom.fields.SFVec2f.prototype.add=function(that){return new x3dom.fields.SFVec2f(this.x+that.x,this.y+that.y);};x3dom.fields.SFVec2f.prototype.subtract=function(that){return new x3dom.fields.SFVec2f(this.x-that.x,this.y-that.y);};x3dom.fields.SFVec2f.prototype.negate=function(){return new x3dom.fields.SFVec2f(-this.x,-this.y);};x3dom.fields.SFVec2f.prototype.dot=function(that){return this.x*that.x+this.y*that.y;};x3dom.fields.SFVec2f.prototype.reflect=function(n){var d2=this.dot(n)*2;return new x3dom.fields.SFVec2f(this.x-d2*n.x,this.y-d2*n.y);};x3dom.fields.SFVec2f.prototype.normalize=function(){var n=this.length();if(n){n=1.0/n;} return new x3dom.fields.SFVec2f(this.x*n,this.y*n);};x3dom.fields.SFVec2f.prototype.multComponents=function(that){return new x3dom.fields.SFVec2f(this.x*that.x,this.y*that.y);};x3dom.fields.SFVec2f.prototype.multiply=function(n){return new x3dom.fields.SFVec2f(this.x*n,this.y*n);};x3dom.fields.SFVec2f.prototype.divideComponents=function(that){return new x3dom.fields.SFVec2f(this.x/that.x,this.y/that.y);};x3dom.fields.SFVec2f.prototype.divide=function(n){var denom=n?(1.0/n):1.0;return new x3dom.fields.SFVec2f(this.x*denom,this.y*denom);};x3dom.fields.SFVec2f.prototype.equals=function(that,eps){return Math.abs(this.x-that.x)x3dom.fields.Eps){var s=Math.sin(a/2)/t;var c=Math.cos(a/2);return new x3dom.fields.Quaternion(axis.x*s,axis.y*s,axis.z*s,c);}else{return new x3dom.fields.Quaternion(0,0,0,1);}};x3dom.fields.Quaternion.prototype.copy=function(){return x3dom.fields.Quaternion.copy(this);};x3dom.fields.Quaternion.prototype.toMatrix=function(){var xx=this.x*this.x;var xy=this.x*this.y;var xz=this.x*this.z;var yy=this.y*this.y;var yz=this.y*this.z;var zz=this.z*this.z;var wx=this.w*this.x;var wy=this.w*this.y;var wz=this.w*this.z;return new x3dom.fields.SFMatrix4f(1-2*(yy+zz),2*(xy-wz),2*(xz+wy),0,2*(xy+wz),1-2*(xx+zz),2*(yz-wx),0,2*(xz-wy),2*(yz+wx),1-2*(xx+yy),0,0,0,0,1);};x3dom.fields.Quaternion.prototype.toAxisAngle=function(){var x=0,y=0,z=0;var s=0,a=0;if(this.w>1){this.normalize();} a=2*Math.acos(this.w);s=Math.sqrt(1-this.w*this.w);if(s==0){x=this.x;y=this.y;z=this.z;}else{x=this.x/s;y=this.y/s;z=this.z/s;} return[new x3dom.fields.SFVec3f(x,y,z),a];};x3dom.fields.Quaternion.prototype.angle=function(){return 2*Math.acos(this.w);};x3dom.fields.Quaternion.prototype.setValue=function(matrix){var tr,s=1;var qt=[0,0,0];var i=0,j=0,k=0;var nxt=[1,2,0];tr=matrix._00+matrix._11+matrix._22;if(tr>0.0){s=Math.sqrt(tr+1.0);this.w=s*0.5;s=0.5/s;this.x=(matrix._21-matrix._12)*s;this.y=(matrix._02-matrix._20)*s;this.z=(matrix._10-matrix._01)*s;}else{if(matrix._11>matrix._00){i=1;}else{i=0;} if(matrix._22>matrix.at(i,i)){i=2;} j=nxt[i];k=nxt[j];s=Math.sqrt(matrix.at(i,i)-(matrix.at(j,j)+matrix.at(k,k))+1.0);qt[i]=s*0.5;s=0.5/s;this.w=(matrix.at(k,j)-matrix.at(j,k))*s;qt[j]=(matrix.at(j,i)+matrix.at(i,j))*s;qt[k]=(matrix.at(k,i)+matrix.at(i,k))*s;this.x=qt[0];this.y=qt[1];this.z=qt[2];} if(this.w>1.0||this.w<-1.0){var errThreshold=1+(x3dom.fields.Eps*100);if(this.w>errThreshold||this.w<-errThreshold){x3dom.debug.logInfo("MatToQuat: BUG: |quat[4]| ("+this.w+") >> 1.0 !");} if(this.w>1.0){this.w=1.0;}else{this.w=-1.0;}}};x3dom.fields.Quaternion.prototype.setFromEuler=function(alpha,beta,gamma){var sx=Math.sin(alpha*0.5);var cx=Math.cos(alpha*0.5);var sy=Math.sin(beta*0.5);var cy=Math.cos(beta*0.5);var sz=Math.sin(gamma*0.5);var cz=Math.cos(gamma*0.5);this.x=(sx*cy*cz)-(cx*sy*sz);this.y=(cx*sy*cz)+(sx*cy*sz);this.z=(cx*cy*sz)-(sx*sy*cz);this.w=(cx*cy*cz)+(sx*sy*sz);};x3dom.fields.Quaternion.prototype.dot=function(that){return this.x*that.x+this.y*that.y+this.z*that.z+this.w*that.w;};x3dom.fields.Quaternion.prototype.add=function(that){return new x3dom.fields.Quaternion(this.x+that.x,this.y+that.y,this.z+that.z,this.w+that.w);};x3dom.fields.Quaternion.prototype.subtract=function(that){return new x3dom.fields.Quaternion(this.x-that.x,this.y-that.y,this.z-that.z,this.w-that.w);};x3dom.fields.Quaternion.prototype.setValues=function(that){this.x=that.x;this.y=that.y;this.z=that.z;this.w=that.w;};x3dom.fields.Quaternion.prototype.equals=function(that,eps){return(this.dot(that)>=1.0-eps);};x3dom.fields.Quaternion.prototype.multScalar=function(s){return new x3dom.fields.Quaternion(this.x*s,this.y*s,this.z*s,this.w*s);};x3dom.fields.Quaternion.prototype.normalize=function(){var d2=this.dot(this);var id=1.0;if(d2){id=1.0/Math.sqrt(d2);} this.x*=id;this.y*=id;this.z*=id;this.w*=id;return this;};x3dom.fields.Quaternion.normalize=function(that){var d2=that.dot(that);var id=1.0;if(d2){id=1.0/Math.sqrt(d2);} that.x*=id;that.y*=id;that.z*=id;that.w*=id;return that;};x3dom.fields.Quaternion.prototype.negate=function(){return new x3dom.fields.Quaternion(-this.x,-this.y,-this.z,-this.w);};x3dom.fields.Quaternion.prototype.inverse=function(){return new x3dom.fields.Quaternion(-this.x,-this.y,-this.z,this.w);};x3dom.fields.Quaternion.prototype.slerp=function(that,t){var cosom=this.dot(that);var rot1;if(cosom<0.0){cosom=-cosom;rot1=that.negate();}else{rot1=new x3dom.fields.Quaternion(that.x,that.y,that.z,that.w);} var scalerot0,scalerot1;if((1.0-cosom)>0.00001){var omega=Math.acos(cosom);var sinom=Math.sin(omega);scalerot0=Math.sin((1.0-t)*omega)/sinom;scalerot1=Math.sin(t*omega)/sinom;}else{scalerot0=1.0-t;scalerot1=t;} return this.multScalar(scalerot0).add(rot1.multScalar(scalerot1));};x3dom.fields.Quaternion.rotateFromTo=function(fromVec,toVec){var from=fromVec.normalize();var to=toVec.normalize();var cost=from.dot(to);if(cost>0.99999){return new x3dom.fields.Quaternion(0,0,0,1);}else if(cost<-0.99999){var cAxis=new x3dom.fields.SFVec3f(1,0,0);var tmp=from.cross(cAxis);if(tmp.length()<0.00001){cAxis.x=0;cAxis.y=1;cAxis.z=0;tmp=from.cross(cAxis);} tmp=tmp.normalize();return x3dom.fields.Quaternion.axisAngle(tmp,Math.PI);} var axis=fromVec.cross(toVec);axis=axis.normalize();var s=Math.sqrt(0.5*(1.0-cost));axis=axis.multiply(s);s=Math.sqrt(0.5*(1.0+cost));return new x3dom.fields.Quaternion(axis.x,axis.y,axis.z,s);};x3dom.fields.Quaternion.prototype.toGL=function(){var val=this.toAxisAngle();return[val[0].x,val[0].y,val[0].z,val[1]];};x3dom.fields.Quaternion.prototype.toString=function(){return this.x+" "+this.y+" "+this.z+", "+this.w;};x3dom.fields.Quaternion.prototype.setValueByStr=function(str){var m=/^\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*$/.exec(str);m=m||[0,1,0,0,0];var quat=x3dom.fields.Quaternion.axisAngle(new x3dom.fields.SFVec3f(+m[1],+m[2],+m[3]),+m[4]);this.x=quat.x;this.y=quat.y;this.z=quat.z;this.w=quat.w;return this;};function _colorParse(str){var red=0.0,green=0.0,blue=0.0;var alpha=1.0;var colorNames={aliceblue:'#f0f8ff',antiquewhite:'#faebd7',aqua:'#00ffff',aquamarine:'#7fffd4',azure:'#f0ffff',beige:'#f5f5dc',bisque:'#ffe4c4',black:'#000000',blanchedalmond:'#ffebcd',blue:'#0000ff',blueviolet:'#8a2be2',brown:'#a52a2a',burlywood:'#deb887',cadetblue:'#5f9ea0',chartreuse:'#7fff00',chocolate:'#d2691e',coral:'#ff7f50',cornflowerblue:'#6495ed',cornsilk:'#fff8dc',crimson:'#dc143c',cyan:'#00ffff',darkblue:'#00008b',darkcyan:'#008b8b',darkgoldenrod:'#b8860b',darkgray:'#a9a9a9',darkgreen:'#006400',darkkhaki:'#bdb76b',darkmagenta:'#8b008b',darkolivegreen:'#556b2f',darkorange:'#ff8c00',darkorchid:'#9932cc',darkred:'#8b0000',darksalmon:'#e9967a',darkseagreen:'#8fbc8f',darkslateblue:'#483d8b',darkslategray:'#2f4f4f',darkturquoise:'#00ced1',darkviolet:'#9400d3',deeppink:'#ff1493',deepskyblue:'#00bfff',dimgray:'#696969',dodgerblue:'#1e90ff',feldspar:'#d19275',firebrick:'#b22222',floralwhite:'#fffaf0',forestgreen:'#228b22',fuchsia:'#ff00ff',gainsboro:'#dcdcdc',ghostwhite:'#f8f8ff',gold:'#ffd700',goldenrod:'#daa520',gray:'#808080',green:'#008000',greenyellow:'#adff2f',honeydew:'#f0fff0',hotpink:'#ff69b4',indianred:'#cd5c5c',indigo:'#4b0082',ivory:'#fffff0',khaki:'#f0e68c',lavender:'#e6e6fa',lavenderblush:'#fff0f5',lawngreen:'#7cfc00',lemonchiffon:'#fffacd',lightblue:'#add8e6',lightcoral:'#f08080',lightcyan:'#e0ffff',lightgoldenrodyellow:'#fafad2',lightgrey:'#d3d3d3',lightgreen:'#90ee90',lightpink:'#ffb6c1',lightsalmon:'#ffa07a',lightseagreen:'#20b2aa',lightskyblue:'#87cefa',lightslateblue:'#8470ff',lightslategray:'#778899',lightsteelblue:'#b0c4de',lightyellow:'#ffffe0',lime:'#00ff00',limegreen:'#32cd32',linen:'#faf0e6',magenta:'#ff00ff',maroon:'#800000',mediumaquamarine:'#66cdaa',mediumblue:'#0000cd',mediumorchid:'#ba55d3',mediumpurple:'#9370d8',mediumseagreen:'#3cb371',mediumslateblue:'#7b68ee',mediumspringgreen:'#00fa9a',mediumturquoise:'#48d1cc',mediumvioletred:'#c71585',midnightblue:'#191970',mintcream:'#f5fffa',mistyrose:'#ffe4e1',moccasin:'#ffe4b5',navajowhite:'#ffdead',navy:'#000080',oldlace:'#fdf5e6',olive:'#808000',olivedrab:'#6b8e23',orange:'#ffa500',orangered:'#ff4500',orchid:'#da70d6',palegoldenrod:'#eee8aa',palegreen:'#98fb98',paleturquoise:'#afeeee',palevioletred:'#d87093',papayawhip:'#ffefd5',peachpuff:'#ffdab9',peru:'#cd853f',pink:'#ffc0cb',plum:'#dda0dd',powderblue:'#b0e0e6',purple:'#800080',red:'#ff0000',rosybrown:'#bc8f8f',royalblue:'#4169e1',saddlebrown:'#8b4513',salmon:'#fa8072',sandybrown:'#f4a460',seagreen:'#2e8b57',seashell:'#fff5ee',sienna:'#a0522d',silver:'#c0c0c0',skyblue:'#87ceeb',slateblue:'#6a5acd',slategray:'#708090',snow:'#fffafa',springgreen:'#00ff7f',steelblue:'#4682b4',tan:'#d2b48c',teal:'#008080',thistle:'#d8bfd8',tomato:'#ff6347',turquoise:'#40e0d0',violet:'#ee82ee',violetred:'#d02090',wheat:'#f5deb3',white:'#ffffff',whitesmoke:'#f5f5f5',yellow:'#ffff00',yellowgreen:'#9acd32'};var rgbMatch=/^rgb\((\d{1,3}),\s{0,1}(\d{1,3}),\s{0,1}(\d{1,3})\)$/.exec(str);if(rgbMatch!==null){red=rgbMatch[1]/255.0;green=rgbMatch[2]/255.0;blue=rgbMatch[3]/255.0;} var rgbaMatch=/^rgba\((\d{1,3}),\s{0,1}(\d{1,3}),\s{0,1}(\d{1,3}),(0+\.?\d*|1\.?0*)\)$/.exec(str);if(rgbaMatch!==null){red=rgbaMatch[1]/255.0;green=rgbaMatch[2]/255.0;blue=rgbaMatch[3]/255.0;alpha=+rgbaMatch[4];} if(colorNames[str]){str=colorNames[str];} if(str.substr&&str.substr(0,1)==="#"){var hex=str.substr(1);var len=hex.length;if(len===8){red=parseInt("0x"+hex.substr(0,2),16)/255.0;green=parseInt("0x"+hex.substr(2,2),16)/255.0;blue=parseInt("0x"+hex.substr(4,2),16)/255.0;alpha=parseInt("0x"+hex.substr(6,2),16)/255.0;}else if(len===6){red=parseInt("0x"+hex.substr(0,2),16)/255.0;green=parseInt("0x"+hex.substr(2,2),16)/255.0;blue=parseInt("0x"+hex.substr(4,2),16)/255.0;}else if(len===4){red=parseInt("0x"+hex.substr(0,1),16)/15.0;green=parseInt("0x"+hex.substr(1,1),16)/15.0;blue=parseInt("0x"+hex.substr(2,1),16)/15.0;alpha=parseInt("0x"+hex.substr(3,1),16)/15.0;}else if(len===3){red=parseInt("0x"+hex.substr(0,1),16)/15.0;green=parseInt("0x"+hex.substr(1,1),16)/15.0;blue=parseInt("0x"+hex.substr(2,1),16)/15.0;}} return{r:red,g:green,b:blue,a:alpha};} x3dom.fields.SFColor=function(r,g,b){if(arguments.length===0){this.r=0;this.g=0;this.b=0;}else{this.r=r;this.g=g;this.b=b;}};x3dom.fields.SFColor.parse=function(str){try{var m=/^\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*,?\s*([+\-]?\d*\.*\d*[eE]?[+\-]?\d*?)\s*$/.exec(str);return new x3dom.fields.SFColor(+m[1],+m[2],+m[3]);} catch(e){return x3dom.fields.SFColor.colorParse(str);}};x3dom.fields.SFColor.copy=function(that){return new x3dom.fields.SFColor(that.r,that.g,that.b);};x3dom.fields.SFColor.prototype.copy=function(){return x3dom.fields.SFColor.copy(this);};x3dom.fields.SFColor.prototype.setHSV=function(h,s,v){x3dom.debug.logWarning("SFColor.setHSV() NYI");};x3dom.fields.SFColor.prototype.getHSV=function(){var h=0,s=0,v=0;x3dom.debug.logWarning("SFColor.getHSV() NYI");return[h,s,v];};x3dom.fields.SFColor.prototype.setValues=function(color){this.r=color.r;this.g=color.g;this.b=color.b;};x3dom.fields.SFColor.prototype.equals=function(that,eps){return Math.abs(this.r-that.r)>>0;};x3dom.fields.SFColorRGBA.colorParse=function(color){var rgba=_colorParse(color);return new x3dom.fields.SFColorRGBA(rgba.r,rgba.g,rgba.b,rgba.a);};x3dom.fields.SFImage=function(w,h,c,arr){if(arguments.length===0||!(arr&&arr.map)){this.width=0;this.height=0;this.comp=0;this.array=[];}else{this.width=w;this.height=h;this.comp=c;var that=this.array;arr.map(function(v){that.push(v);},this.array);}};x3dom.fields.SFImage.parse=function(str){var img=new x3dom.fields.SFImage();img.setValueByStr(str);return img;};x3dom.fields.SFImage.copy=function(that){var destination=new x3dom.fields.SFImage();destination.width=that.width;destination.height=that.height;destination.comp=that.comp;destination.setPixels(that.getPixels());return destination;};x3dom.fields.SFImage.prototype.copy=function(){return x3dom.fields.SFImage.copy(this);};x3dom.fields.SFImage.prototype.setValueByStr=function(str){var mc=str.match(/(\w+)/g);var n=mc.length;this.array=[];if(n>2){this.width=+mc[0];this.height=+mc[1];this.comp=+mc[2];}else{this.width=0;this.height=0;this.comp=0;return;} var len,i;var r,g,b,a;var radix=10;for(i=3;i>8&255;g=inp&255;this.array.push(r,g);}else if(this.comp===3){r=inp>>16&255;g=inp>>8&255;b=inp&255;this.array.push(r,g,b);}else if(this.comp===4){r=inp>>24&255;g=inp>>16&255;b=inp>>8&255;a=inp&255;this.array.push(r,g,b,a);}}};x3dom.fields.SFImage.prototype.setPixel=function(x,y,color){var startIdx=(y*this.width+x)*this.comp;if(this.comp===1&&startIdx0);} return false;};x3dom.fields.MFNode.prototype.addLink=function(node){this.nodes.push(node);return true;};x3dom.fields.MFNode.prototype.rmLink=function(node){for(var i=0,n=this.nodes.length;ix3dom.fields.Eps){r=1.0/this.dir.x;te=(low.x-this.pos.x)*r;tl=(high.x-this.pos.x)*r;if(tlisect){isect=te;}}else if(this.dir.x<-x3dom.fields.Eps){r=1.0/this.dir.x;te=(high.x-this.pos.x)*r;tl=(low.x-this.pos.x)*r;if(tlisect){isect=te;}}else if(this.pos.xhigh.x){return false;} if(this.dir.y>x3dom.fields.Eps){r=1.0/this.dir.y;te=(low.y-this.pos.y)*r;tl=(high.y-this.pos.y)*r;if(tlisect){isect=te;} if(isect-out>=x3dom.fields.Eps){return false;}}else if(this.dir.y<-x3dom.fields.Eps){r=1.0/this.dir.y;te=(high.y-this.pos.y)*r;tl=(low.y-this.pos.y)*r;if(tlisect){isect=te;} if(isect-out>=x3dom.fields.Eps){return false;}}else if(this.pos.yhigh.y){return false;} if(this.dir.z>x3dom.fields.Eps){r=1.0/this.dir.z;te=(low.z-this.pos.z)*r;tl=(high.z-this.pos.z)*r;if(tlisect){isect=te;}}else if(this.dir.z<-x3dom.fields.Eps){r=1.0/this.dir.z;te=(high.z-this.pos.z)*r;tl=(low.z-this.pos.z)*r;if(tlisect){isect=te;}}else if(this.pos.zhigh.z){return false;} this.enter=isect;this.exit=out;return(isect-outmin.x){this.min.x=min.x;} if(this.min.y>min.y){this.min.y=min.y;} if(this.min.z>min.z){this.min.z=min.z;} if(this.max.x=b){xmax+=a;xmin+=b;}else{xmax+=b;xmin+=a;} a=this.max.y*m._01;b=this.min.y*m._01;if(a>=b){xmax+=a;xmin+=b;}else{xmax+=b;xmin+=a;} a=this.max.z*m._02;b=this.min.z*m._02;if(a>=b){xmax+=a;xmin+=b;}else{xmax+=b;xmin+=a;} a=this.max.x*m._10;b=this.min.x*m._10;if(a>=b){ymax+=a;ymin+=b;}else{ymax+=b;ymin+=a;} a=this.max.y*m._11;b=this.min.y*m._11;if(a>=b){ymax+=a;ymin+=b;}else{ymax+=b;ymin+=a;} a=this.max.z*m._12;b=this.min.z*m._12;if(a>=b){ymax+=a;ymin+=b;}else{ymax+=b;ymin+=a;} a=this.max.x*m._20;b=this.min.x*m._20;if(a>=b){zmax+=a;zmin+=b;}else{zmax+=b;zmin+=a;} a=this.max.y*m._21;b=this.min.y*m._21;if(a>=b){zmax+=a;zmin+=b;}else{zmax+=b;zmin+=a;} a=this.max.z*m._22;b=this.min.z*m._22;if(a>=b){zmax+=a;zmin+=b;}else{zmax+=b;zmin+=a;} this.min.x=xmin;this.min.y=ymin;this.min.z=zmin;this.max.x=xmax;this.max.y=ymax;this.max.z=zmax;this.updateInternals();};x3dom.fields.BoxVolume.prototype.transformFrom=function(m,other){var xmin,ymin,zmin;var xmax,ymax,zmax;xmin=xmax=m._03;ymin=ymax=m._13;zmin=zmax=m._23;var a=other.max.x*m._00;var b=other.min.x*m._00;if(a>=b){xmax+=a;xmin+=b;}else{xmax+=b;xmin+=a;} a=other.max.y*m._01;b=other.min.y*m._01;if(a>=b){xmax+=a;xmin+=b;}else{xmax+=b;xmin+=a;} a=other.max.z*m._02;b=other.min.z*m._02;if(a>=b){xmax+=a;xmin+=b;}else{xmax+=b;xmin+=a;} a=other.max.x*m._10;b=other.min.x*m._10;if(a>=b){ymax+=a;ymin+=b;}else{ymax+=b;ymin+=a;} a=other.max.y*m._11;b=other.min.y*m._11;if(a>=b){ymax+=a;ymin+=b;}else{ymax+=b;ymin+=a;} a=other.max.z*m._12;b=other.min.z*m._12;if(a>=b){ymax+=a;ymin+=b;}else{ymax+=b;ymin+=a;} a=other.max.x*m._20;b=other.min.x*m._20;if(a>=b){zmax+=a;zmin+=b;}else{zmax+=b;zmin+=a;} a=other.max.y*m._21;b=other.min.y*m._21;if(a>=b){zmax+=a;zmin+=b;}else{zmax+=b;zmin+=a;} a=other.max.z*m._22;b=other.min.z*m._22;if(a>=b){zmax+=a;zmin+=b;}else{zmax+=b;zmin+=a;} this.min.x=xmin;this.min.y=ymin;this.min.z=zmin;this.max.x=xmax;this.max.y=ymax;this.max.z=zmax;this.updateInternals();this.valid=true;};x3dom.fields.FrustumVolume=function(clipMat){this.planeNormals=[];this.planeDistances=[];this.directionIndex=[];if(arguments.length===0){return;} var planeEquation=[];for(var i=0;i<6;i++){this.planeNormals[i]=new x3dom.fields.SFVec3f(0,0,0);this.planeDistances[i]=0;this.directionIndex[i]=0;planeEquation[i]=new x3dom.fields.SFVec4f(0,0,0,0);} planeEquation[0].x=clipMat._30-clipMat._00;planeEquation[0].y=clipMat._31-clipMat._01;planeEquation[0].z=clipMat._32-clipMat._02;planeEquation[0].w=clipMat._33-clipMat._03;planeEquation[1].x=clipMat._30+clipMat._00;planeEquation[1].y=clipMat._31+clipMat._01;planeEquation[1].z=clipMat._32+clipMat._02;planeEquation[1].w=clipMat._33+clipMat._03;planeEquation[2].x=clipMat._30+clipMat._10;planeEquation[2].y=clipMat._31+clipMat._11;planeEquation[2].z=clipMat._32+clipMat._12;planeEquation[2].w=clipMat._33+clipMat._13;planeEquation[3].x=clipMat._30-clipMat._10;planeEquation[3].y=clipMat._31-clipMat._11;planeEquation[3].z=clipMat._32-clipMat._12;planeEquation[3].w=clipMat._33-clipMat._13;planeEquation[4].x=clipMat._30+clipMat._20;planeEquation[4].y=clipMat._31+clipMat._21;planeEquation[4].z=clipMat._32+clipMat._22;planeEquation[4].w=clipMat._33+clipMat._23;planeEquation[5].x=clipMat._30-clipMat._20;planeEquation[5].y=clipMat._31-clipMat._21;planeEquation[5].z=clipMat._32-clipMat._22;planeEquation[5].w=clipMat._33-clipMat._23;for(i=0;i<6;i++){var vectorLength=Math.sqrt(planeEquation[i].x*planeEquation[i].x+ planeEquation[i].y*planeEquation[i].y+ planeEquation[i].z*planeEquation[i].z);planeEquation[i].x/=vectorLength;planeEquation[i].y/=vectorLength;planeEquation[i].z/=vectorLength;planeEquation[i].w/=-vectorLength;} var updateDirectionIndex=function(normalVec){var ind=0;if(normalVec.x>0)ind|=1;if(normalVec.y>0)ind|=2;if(normalVec.z>0)ind|=4;return ind;};this.planeNormals[3].setValues(planeEquation[0]);this.planeDistances[3]=planeEquation[0].w;this.directionIndex[3]=updateDirectionIndex(this.planeNormals[3]);this.planeNormals[2].setValues(planeEquation[1]);this.planeDistances[2]=planeEquation[1].w;this.directionIndex[2]=updateDirectionIndex(this.planeNormals[2]);this.planeNormals[5].setValues(planeEquation[2]);this.planeDistances[5]=planeEquation[2].w;this.directionIndex[5]=updateDirectionIndex(this.planeNormals[5]);this.planeNormals[4].setValues(planeEquation[3]);this.planeDistances[4]=planeEquation[3].w;this.directionIndex[4]=updateDirectionIndex(this.planeNormals[4]);this.planeNormals[0].setValues(planeEquation[4]);this.planeDistances[0]=planeEquation[4].w;this.directionIndex[0]=updateDirectionIndex(this.planeNormals[0]);this.planeNormals[1].setValues(planeEquation[5]);this.planeDistances[1]=planeEquation[5].w;this.directionIndex[1]=updateDirectionIndex(this.planeNormals[1]);};x3dom.fields.FrustumVolume.prototype.intersect=function(vol,planeMask){if(this.planeNormals.length<6){x3dom.debug.logWarning("FrustumVolume not initialized!");return false;} var that=this;var min=vol.min,max=vol.max;var setDirectionIndexPoint=function(index){var pnt=new x3dom.fields.SFVec3f(0,0,0);if(index&1){pnt.x=min.x;} else{pnt.x=max.x;} if(index&2){pnt.y=min.y;} else{pnt.y=max.y;} if(index&4){pnt.z=min.z;} else{pnt.z=max.z;} return pnt;};var pntIsInHalfSpace=function(i,pnt){var s=that.planeNormals[i].dot(pnt)-that.planeDistances[i];return(s>=0);};var isInHalfSpace=function(i){var p=setDirectionIndexPoint(that.directionIndex[i]);return pntIsInHalfSpace(i,p);};var isOutHalfSpace=function(i){var p=setDirectionIndexPoint(that.directionIndex[i]^7);return!pntIsInHalfSpace(i,p);};var mask=1;if(planeMask<0)planeMask=0;for(var i=0;i<6;i++,mask<<=1){if((planeMask&mask)!=0) continue;if(isOutHalfSpace(i)) return-1;if(isInHalfSpace(i)) planeMask|=mask;} return planeMask;};x3dom.docs={};x3dom.docs.specURLMap={CADGeometry:"CADGeometry.html",Core:"core.html",DIS:"dis.html",CubeMapTexturing:"env_texture.html",EnvironmentalEffects:"enveffects.html",EnvironmentalSensor:"envsensor.html",Followers:"followers.html",Geospatial:"geodata.html",Geometry2D:"geometry2D.html",Geometry3D:"geometry3D.html",Grouping:"group.html","H-Anim":"hanim.html",Interpolation:"interp.html",KeyDeviceSensor:"keyboard.html",Layering:"layering.html",Layout:"layout.html",Lighting:"lighting.html",Navigation:"navigation.html",Networking:"networking.html",NURBS:"nurbs.html",ParticleSystems:"particle_systems.html",Picking:"picking.html",PointingDeviceSensor:"pointingsensor.html",Rendering:"rendering.html",RigidBodyPhysics:"rigid_physics.html",Scripting:"scripting.html",Shaders:"shaders.html",Shape:"shape.html",Sound:"sound.html",Text:"text.html",Texturing3D:"texture3D.html",Texturing:"texturing.html",Time:"time.html",EventUtilities:"utils.html",VolumeRendering:"volume.html"};x3dom.docs.specBaseURL="http://www.web3d.org/x3d/specifications/ISO-IEC-19775-1.2-X3D-AbstractSpecification/Part01/components/";x3dom.docs.getNodeTreeInfo=function(){var tn,t;var types="";var objInArray=function(array,obj){for(var i=0;i"+ t+"   "+ x3dom.nodeTypes[t]._compName+"
";for(var i in x3dom.nodeTypes[t].childTypes[t]){dump(x3dom.nodeTypes[t].childTypes[t][i],indent+1);}};for(tn in x3dom.nodeTypes){var t=x3dom.nodeTypes[tn];if(t.childTypes===undefined){t.childTypes={};} while(t.superClass){if(t.superClass.childTypes[t.superClass._typeName]===undefined){t.superClass.childTypes[t.superClass._typeName]=[];} if(!objInArray(t.superClass.childTypes[t.superClass._typeName],t._typeName)){t.superClass.childTypes[t.superClass._typeName].push(t._typeName);} t=t.superClass;}} dump("X3DNode",0);return"
"+types+"
";};x3dom.docs.getComponentInfo=function(){var components=[];var component;var result="";var c,cn;for(c in x3dom.components){components.push(c);} components.sort();for(cn in components){c=components[cn];component=x3dom.components[c];result+="

"+ c+"

";result+="
    ";for(var t in component){result+="
  • "+ t+"
  • ";} result+="
";} return result;};"use strict";x3dom.JSONParser=function(scene) {this.x3djsonNS="http://www.web3d.org/specifications/x3d-namespace";};x3dom.JSONParser.prototype.constructor=x3dom.JSONParser;x3dom.JSONParser.prototype.parseJavaScript=function(jsobj){var child=this.CreateElement('X3D');this.ConvertToX3DOM(jsobj,"",child);return child;};x3dom.JSONParser.prototype.elementSetAttribute=function(element,key,value){if(key==='SON schema'){}else if(key==='ncoding'){}else{if(typeof element.setAttribute==='function'){element.setAttribute(key,value);}}};x3dom.JSONParser.prototype.ConvertChildren=function(parentkey,object,element){var key;for(key in object){if(typeof object[key]==='object'){if(isNaN(parseInt(key))){this.ConvertObject(key,object,element,parentkey.substr(1));}else{this.ConvertToX3DOM(object[key],key,element,parentkey.substr(1));}}}};x3dom.JSONParser.prototype.CreateElement=function(key,containerField){var child=null;if(typeof this.x3djsonNS==='undefined'){child=document.createElement(key);}else{child=document.createElementNS(this.x3djsonNS,key);if(child===null||typeof child==='undefined'){console.error('Trouble creating element for',key);child=document.createElement(key);}} if(typeof containerField!=='undefined'){this.elementSetAttribute(child,'containerField',containerField);} return child;};x3dom.JSONParser.prototype.CDATACreateFunction=function(document,element,str){var y=str.trim().replace(/\\"/g,"\\\"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&");do{str=y;y=str.replace(/'([^'\r\n]*)\n([^']*)'/g,"'$1\\n$2'");if(str!==y){}}while(y!=str);var domParser=new DOMParser();var cdataStr='';var scriptDoc=domParser.parseFromString(cdataStr,'application/xml');var cdata=scriptDoc.children[0].childNodes[1];element.appendChild(cdata);};x3dom.JSONParser.prototype.ConvertObject=function(key,object,element,containerField){var child;if(object!==null&&typeof object[key]==='object'){if(key.startsWith('@')){this.ConvertToX3DOM(object[key],key,element);}else if(key.startsWith('-')){this.ConvertChildren(key,object[key],element);}else if(key==='#comment'){for(var c in object[key]){child=document.createComment(this.CommentStringToXML(object[key][c]));element.appendChild(child);}}else if(key==='#sourceText'){this.CDATACreateFunction(document,element,object[key].join("\r\n")+"\r\n");}else{if(key==='connect'||key==='fieldValue'||key==='field'||key==='meta'||key==='component'){for(var childkey in object[key]){if(typeof object[key][childkey]==='object'){child=this.CreateElement(key,containerField);this.ConvertToX3DOM(object[key][childkey],childkey,child);element.appendChild(child);element.appendChild(document.createTextNode("\n"));}}}else{child=this.CreateElement(key,containerField);this.ConvertToX3DOM(object[key],key,child);element.appendChild(child);element.appendChild(document.createTextNode("\n"));}}}};x3dom.JSONParser.prototype.CommentStringToXML=function(str){var y=str;str=str.replace(/\\\\/g,'\\');if(y!==str){} return str;};x3dom.JSONParser.prototype.SFStringToXML=function(str){var y=str;str=str.replace(/\\/g,'\\\\');str=str.replace(/"/g,'\\\"');if(y!==str){} return str;};x3dom.JSONParser.prototype.JSONStringToXML=function(str){var y=str;str=str.replace(/\\/g,'\\\\');str=str.replace(/\n/g,'\\n');if(y!==str){} return str;};x3dom.JSONParser.prototype.ConvertToX3DOM=function(object,parentkey,element,containerField){var key;var localArray=[];var isArray=false;var arrayOfStrings=false;for(key in object){if(isNaN(parseInt(key))){isArray=false;}else{isArray=true;} if(isArray){if(typeof object[key]==='number'){localArray.push(object[key]);}else if(typeof object[key]==='string'){localArray.push(object[key]);arrayOfStrings=true;}else if(typeof object[key]==='boolean'){localArray.push(object[key]);}else if(typeof object[key]==='object'){this.ConvertToX3DOM(object[key],key,element);}else if(typeof object[key]==='undefined'){}else{console.error("Unknown type found in array "+typeof object[key]);}}else if(typeof object[key]==='object'){if(key==='X3D'){this.ConvertToX3DOM(object[key],key,element);}else{this.ConvertObject(key,object,element);}}else if(typeof object[key]==='number'){this.elementSetAttribute(element,key.substr(1),object[key]);}else if(typeof object[key]==='string'){if(key!=='#comment'){this.elementSetAttribute(element,key.substr(1),this.JSONStringToXML(object[key]));}else{var child=document.createComment(this.CommentStringToXML(object[key]));element.appendChild(child);}}else if(typeof object[key]==='boolean'){this.elementSetAttribute(element,key.substr(1),object[key]);}else if(typeof object[key]==='undefined'){}else{console.error("Unknown type found in object "+typeof object[key]);console.error(object);}} if(isArray){if(parentkey.startsWith('@')){if(arrayOfStrings){for(var str in localArray){localArray[str]=this.SFStringToXML(localArray[str]);} this.elementSetAttribute(element,parentkey.substr(1),'"'+localArray.join('" "')+'"');}else{this.elementSetAttribute(element,parentkey.substr(1),localArray.join(" "));}}} return element;};x3dom.PROTOS=function(){this.protos={};this.names={};this.protoField={};this.scriptField={};this.interfaceField={};this.envField={};this.scopecount=0;this.privatescope=[];this.defs={};this.founddef=null;this.SFNodes={"-appearance":1,"-body":1,"-child":1,"-collidable":1,"-collider":1,"-color":1,"-composableRenderStyle":1,"-coord":1,"-emitter":1,"-fillProperties":1,"-fogCoord":1,"-fontStyle":1,"-geometry":1,"-geoOrigin":1,"-layout":1,"-lineProperties":1,"-massDensityModel":1,"-material":1,"-metadata":1,"-normal":1,"-nurbsCurve":1,"-nurbsCurve2D":1,"-pickingGeometry":1,"-renderStyle":1,"-shape":1,"-source":1,"-texCoord":1,"-texCoordNurbs":1,"-texCoordRamp":1,"-texture":1,"-texture2D":1,"-texture2DMulti":1,"-texture3D":1,"-textureProperties":1,"-textureTransform":1,"-transferFunction":1,"-viewport":1};} x3dom.PROTOS.prototype={flattenerArray:function(object,parentArray){var newobject=[];var offset=0;for(var p in object){var possibleArray=this.flattener(object[p],newobject,object.length);if(Array.isArray(possibleArray)){for(var q in possibleArray){newobject[parseInt(p)+offset+parseInt(q)]=possibleArray[q];} offset+=possibleArray.length-1;}else{newobject[parseInt(p)+offset]=possibleArray;}} return newobject;},flattenerObject:function(object,parentArray,arrayLen){var newobject={};for(var p in object){var possibleArray=this.flattener(object[p],parentArray,arrayLen);if(Array.isArray(possibleArray)){if(this.SFNodes[p]){newobject[p]=possibleArray[0];if(possibleArray.length>1){parentArray[arrayLen]={"Switch":{"@whichChoice":-1,"-children":[{"Group":{"-children":[]}}]}};for(var i=1;i0){scope=scope.substring(decl);} return scope;},scopeLength:function(){return this.privatescope.length;},upScope:function(i){return this.privatescope.slice(0,this.privatescope.length-i).join("_");},setValueFromInterface:function(field,object,objectfield){var fieldname_field_scope=this.getInterface(field);var prefix="@";if(typeof fieldname_field_scope!='undefined'&&typeof fieldname_field_scope[0]!='undefined'){prefix=fieldname_field_scope[0].substr(0,1);} if(prefix==='@'&&objectfield==='children'){prefix='-';} if(prefix==='-'&&objectfield==='value'){prefix="@";} objectfield=prefix+objectfield;if(typeof fieldname_field_scope!='undefined'&&typeof fieldname_field_scope[1]!='undefined'&&typeof fieldname_field_scope[0]!='undefined'&&typeof fieldname_field_scope[1][fieldname_field_scope[0]]!='undefined'){var value=fieldname_field_scope[1][fieldname_field_scope[0]];if(Array.isArray(value)&&fieldname_field_scope[1]["@type"]==="SFNode"&&objectfield!=='-children'){console.error("SFNode is array, reducing",value);value=value[0];} if(!Array.isArray(value)&&objectfield==='-children'){objectfield="@value";} object[objectfield]=value;return[fieldname_field_scope[1]["@type"],fieldname_field_scope[2]];} return undefined;},getObjectField:function(f,type){var objectfield="value";if(type.indexOf("FNode")===1){objectfield="children";} for(var a in f){if(a==='@value'||a==='-children'){objectfield=a.substr(1);}} return objectfield;},findFieldByName:function(fields,objectfield){for(var field in fields){var f=fields[field];var fieldname=f["@name"];if(fieldname===objectfield){return f;}} throw"Can't find "+objectfield;},getScriptFieldFieldTypeFieldByNameAttribute:function(fields,objectfield){var f=this.findFieldByName(fields,objectfield);var fieldname=f["@name"];var type=f["@type"];objectfield=this.getObjectField(f,type);return[f,fieldname,type,objectfield];},getScriptFieldFieldTypeField:function(fields,field){var f=fields[field];var fieldname=f["@name"];var type=f["@type"];var objectfield=this.getObjectField(f,type);return[f,fieldname,type,objectfield];},setScriptFields:function(fields,def){var scope=this.getScope();for(var field in fields){var field_name_field_type_objectfield_name=this.getScriptFieldFieldTypeField(fields,field);var f=field_name_field_type_objectfield_name[0];var fieldname=field_name_field_type_objectfield_name[1];var type=field_name_field_type_objectfield_name[2];var objectfield=field_name_field_type_objectfield_name[3];var type_scope=this.setValueFromInterface(fieldname,f,objectfield);this.setScriptField(scope,fieldname,f,objectfield,type,def);if(typeof type_scope!=='undefined'){this.setScriptField(type_scope[1],fieldname,f,objectfield,type,def);}}},setScriptField:function(scope,field,f,objectfield,type,def){if(typeof this.scriptField[this.getField(scope,field)]==='undefined'){this.scriptField[this.getField(scope,field)]=[];} this.scriptField[this.getField(scope,field)][this.scriptField[this.getField(scope,field)].length]=[f,objectfield,type,def];},setEnv:function(scope,protoField,newobject,nodeField,type,newdef){var fieldname_field_scope=this.getInterface(protoField);if(typeof fieldname_field_scope!=='undefined'){scope=fieldname_field_scope[2];} if(typeof this.envField[this.getField(scope,protoField)]==='undefined'){this.envField[this.getField(scope,protoField)]=[];} this.envField[this.getField(scope,protoField)][this.envField[this.getField(scope,protoField)].length]=[newobject,nodeField,type,newdef];},getEnv:function(scope,protoField){return this.envField[this.getField(scope,protoField)];},setConnectField:function(scope,field,newobject,objectfield,type,newdef){if(typeof this.protoField[this.getField(scope,field)]==='undefined'){this.protoField[this.getField(scope,field)]=[];} this.protoField[this.getField(scope,field)][this.protoField[this.getField(scope,field)].length]=[newobject,objectfield,type,newdef];},setConnectFields:function(object,p,newobject){var def=object["@DEF"];var newdef=this.saveDef(def);var connect=object[p]["connect"];var scope=this.getScope();for(var cfield in connect){var f=connect[cfield];if(f){var field=this.getScope(f["@protoField"]);var objectfield=f["@nodeField"];var type_scope=this.setValueFromInterface(field,newobject,objectfield);var type=undefined;if(typeof type_scope!=='undefined'){type=type_scope[0];this.setEnv(scope,field,newobject,objectfield,type,newdef);this.setConnectField(scope,field,newobject,objectfield,type,newdef);this.setConnectField(type_scope[1],field,newobject,objectfield,type,newdef);}else{this.setEnv(scope,field,newobject,objectfield,type,newdef);this.setConnectField(scope,field,newobject,objectfield,type,newdef);}}}},setScriptConnectFields:function(file,object,p,newobject){var connect=object[p]["connect"];var scope=this.getScope();var def=object["@DEF"];newobject["field"]=this.realPrototypeExpander(file,object["field"],true);var newdef=newobject["@DEF"];for(var cfield in connect){var f=connect[cfield];if(f){var field=this.getScope(f["@protoField"]);var objectfield=f["@nodeField"];var field_name_field_type_objectfield_name=this.getScriptFieldFieldTypeFieldByNameAttribute(newobject["field"],objectfield);f=field_name_field_type_objectfield_name[0];var fieldname=field_name_field_type_objectfield_name[1];var type=field_name_field_type_objectfield_name[2];objectfield=field_name_field_type_objectfield_name[3];var type_scope=this.setValueFromInterface(field,f,objectfield);if(typeof type_scope!=='undefined'){type=type_scope[0];this.setScriptField(scope,field,f,objectfield,type,def);this.setScriptField(type_scope[1],field,f,objectfield,type,def);}else{this.setScriptField(scope,field,f,objectfield,type,def);}}}},getInterface:function(field){for(var i=0;i=0){protoname=u.substring(nameIndex+1);} try{protoexp.loadedProto(data,protoname,obj,u,protoexp,function(nuobject){if(typeof alert==='function'){} done(p,nuobject,protoexp);});}catch(e){console.error("Error searching for proto",e);}},processURLs:function(localArray,path){var url;for(url in localArray){if(localArray[url].indexOf("http://")===0||localArray[url].indexOf("https://")===0){}else if(localArray[url].indexOf("urn:web3d:media:textures/panoramas/")===0){var ls=localArray[url].lastIndexOf("/");if(ls>0){localArray[url]='examples/Basic/UniversalMediaPanoramas/'+localArray[url].substring(ls+1);}}else{var p=localArray[url].indexOf('#');var pe=path.lastIndexOf('/');var pc=path;if(pe>=0){pc=path.substring(0,pe);} while(localArray[url].startsWith("../")){localArray[url]=localArray[url].substr(3);var pe=pc.lastIndexOf('/');if(pe>=0){pc=pc.substring(0,pe);}else{pc="";}} if(p==0){localArray[url]=path+localArray[url];}else{localArray[url]=pc+"/"+localArray[url];}} var h=localArray[url].lastIndexOf("#");var hash="";if(h>=0){hash=localArray[url].substring(h);localArray[url]=localArray[url].substring(0,h);} var wrl=localArray[url].lastIndexOf(".wrl");if(wrl===localArray[url].length-4){localArray[url]=localArray[url].substring(0,wrl)+".json"+hash;} var wrz=localArray[url].lastIndexOf(".wrz");if(wrz===localArray[url].length-4){localArray[url]=localArray[url].substring(0,wrz)+".json"+hash;}} return localArray;},loadURLs:function(loadpath,urls,loadedCallback,protoexp,done,externProtoDeclare,obj){if(typeof urls!=='undefined'){urls=this.processURLs(urls,loadpath);for(var u in urls){try{var url=urls[u];(function(url){var p=url.indexOf("://");var protocol="file";var host="localhost";var path="/"+loadpath;if(p>0){protocol=url.substring(0,p);var pa=url.indexOf("/",p+3);host=url.substring(p+3,pa);path=url.substring(pa);} if(protocol==="http"){if(typeof http!=='undefined'){http.get({host:host,path:path},function(res){var data='';res.on('data',function(d){data+=d;});res.on('end',function(){loadedCallback(data,url,protoexp,done,externProtoDeclare,obj);});});}else{var request=new XMLHttpRequest();request.open('GET',url,false);request.send(null);if(request.status===200){var data=request.responseText;loadedCallback(data,url,protoexp,done,externProtoDeclare,obj);}}}else if(protocol==="https"){if(typeof https!=='undefined'){https.get({host:host,path:path},function(res){var data='';res.on('data',function(d){data+=d;});res.on('end',function(){loadedCallback(data,url,protoexp,done,externProtoDeclare,obj);});});}else{var request=new XMLHttpRequest();request.open('GET',url,false);request.send(null);if(request.status===200){var data=request.responseText;loadedCallback(data,url,protoexp,done,externProtoDeclare,obj);}}}else if(typeof fs!=='undefined'&&!protocol.startsWith("http")){var hash=url.indexOf("#");if(hash>0){url=url.substring(0,hash);} try{var data=fs.readFileSync(url);loadedCallback(data.toString(),url,protoexp,done,externProtoDeclare,obj);}catch(e){var filename=url;if(filename.endsWith(".json")){filename=filename.substring(0,filename.lastIndexOf("."))+".x3d";if(typeof runAndSend==='function'){runAndSend(['---silent',filename],function(jsobj){data=JSON.stringify(jsobj);loadedCallback(data,filename,protoexp,done,externProtoDeclare,obj);});}}}}else{var request=new XMLHttpRequest();request.open('GET',url,false);request.send(null);if(request.status===200){var data=request.responseText;loadedCallback(data,url,protoexp,done,externProtoDeclare,obj);}else{console.error("Didn't load",url,". No file system or http request.");}}})(url);}catch(e){console.error(e);}}}},load:function(p,file,object,protoexp,done){var obj=object[p];var url=obj["@url"];this.loadURLs(file,url,protoexp.doLoad,protoexp,done,p,obj);},externalPrototypeExpander:function(file,object){if(typeof object==="object"){var newobject=null;if(Array.isArray(object)){newobject=[];}else{newobject={};} for(var p in object){if(p==="ExternProtoDeclare"){this.load(p,file,object,this,function(p,newobj,protoexp){if(newobj!=null&&typeof newobj!='undefined'){newobject["ProtoDeclare"]=protoexp.externalPrototypeExpander(file,newobj)["ProtoDeclare"];}});}else{newobject[p]=this.externalPrototypeExpander(file,object[p]);}} var expectedreturn=Object.keys(object).length;while(expectedreturn>Object.keys(newobject).length+1);{setTimeout(function(){},50);} return newobject;}else{return object;}}};x3dom.protoExpander=new x3dom.PROTOS();x3dom.shader={};x3dom.shader.PICKING="picking";x3dom.shader.PICKING_24="picking24";x3dom.shader.PICKING_ID="pickingId";x3dom.shader.PICKING_COLOR="pickingColor";x3dom.shader.PICKING_TEXCOORD="pickingTexCoord";x3dom.shader.FRONTGROUND_TEXTURE="frontgroundTexture";x3dom.shader.BACKGROUND_TEXTURE="backgroundTexture";x3dom.shader.BACKGROUND_SKYTEXTURE="backgroundSkyTexture";x3dom.shader.BACKGROUND_CUBETEXTURE="backgroundCubeTexture";x3dom.shader.BACKGROUND_CUBETEXTURE_DDS="backgroundCubeTextureDDS";x3dom.shader.BLUR="blur";x3dom.shader.DEPTH="depth";x3dom.shader.NORMAL="normal";x3dom.shader.TEXTURE_REFINEMENT="textureRefinement";x3dom.shader.SSAO="ssao";x3dom.shader.material=function(){var shaderPart="uniform vec3 diffuseColor;\n"+"uniform vec3 specularColor;\n"+"uniform vec3 emissiveColor;\n"+"uniform float shininess;\n"+"uniform float transparency;\n"+"uniform float ambientIntensity;\n";return shaderPart;};x3dom.shader.physicalMaterial=function(){var shaderPart="uniform vec3 baseColorFacor;\n"+"uniform vec3 emissiveFactor;\n"+"uniform float metallicFactor;\n"+"uniform float roughnessFactor;\n";return shaderPart;};x3dom.shader.twoSidedMaterial=function(){var shaderPart="uniform vec3 backDiffuseColor;\n"+"uniform vec3 backSpecularColor;\n"+"uniform vec3 backEmissiveColor;\n"+"uniform float backShininess;\n"+"uniform float backTransparency;\n"+"uniform float backAmbientIntensity;\n";return shaderPart;};x3dom.shader.fog=function(){var shaderPart="uniform vec3 fogColor;\n"+"uniform float fogType;\n"+"uniform float fogRange;\n"+"varying vec3 fragEyePosition;\n"+"float calcFog(in vec3 eye) {\n"+" float f0 = 0.0;\n"+" if(fogType == 0.0) {\n"+" if(length(eye) < fogRange){\n"+" f0 = (fogRange-length(eye)) / fogRange;\n"+" }\n"+" }else{\n"+" if(length(eye) < fogRange){\n"+" f0 = exp(-length(eye) / (fogRange-length(eye) ) );\n"+" }\n"+" }\n"+" f0 = clamp(f0, 0.0, 1.0);\n"+" return f0;\n"+"}\n";return shaderPart;};x3dom.shader.clipPlanes=function(numClipPlanes){var shaderPart="",c;for(c=0;c= absDir.y && absDir.x >= absDir.z) {\n"+" if(dir.x < 0.0) {\n"+" uv.x = 1.0 - (((dir.z/absDir.x) + 1.0) * 0.5);\n"+" uv.y = 1.0 - (((-dir.y/absDir.x) + 1.0) * 0.5);\n"+" } else {\n"+" uv.x = 1.0 - (((-dir.z/absDir.x) + 1.0) * 0.5);\n"+" uv.y = 1.0 - (((-dir.y/absDir.x) + 1.0) * 0.5);\n"+" }\n"+" } else if( absDir.y >= absDir.x && absDir.y >= absDir.z) {\n"+" if(dir.y < 0.0) {\n"+" uv.x = ((dir.x/absDir.y) + 1.0) * 0.5;\n"+" uv.y = ((-dir.z/absDir.y) + 1.0) * 0.5;\n"+" } else {\n"+" uv.x = ((dir.x/absDir.y) + 1.0) * 0.5;\n"+" uv.y = ((dir.z/absDir.y) + 1.0) * 0.5;\n"+"if(uv.y == 0.0) { uv.x = 1.0; uv.y = 0.0; }\n"+" }\n"+" } else if( absDir.z >= absDir.x && absDir.z >= absDir.y) {\n"+" if(dir.z < 0.0) {\n"+" uv.x = (((-dir.x/absDir.z) + 1.0) * 0.5);\n"+" uv.y = 1.0 - (((-dir.y/absDir.z) + 1.0) * 0.5);\n"+" } else {\n"+" uv.x = ((dir.x/absDir.z) + 1.0) * 0.5;\n"+" uv.y = 1.0 - (((-dir.y/absDir.z) + 1.0) * 0.5);\n"+" }\n"+" }\n"+" float a = pow(64.0,2.0) / pow(64.0,3.0);\n"+" uv.x = a * pow(uv.x, 3.0) + uv.x;\n"+" uv.y = a * pow(uv.y, 3.0) + uv.y;\n"+" return uv;\n"+"}\n";shaderPart+="float calcMipLevel( vec2 uv ) {\n"+" vec2 dx_vtc = dFdx(uv) * 64.0;\n"+" vec2 dy_vtc = dFdy(uv) * 64.0;\n"+" float delta_max_sqr = max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc));\n"+" return 0.5 * log2(delta_max_sqr);\n"+"}\n";shaderPart+="vec3 fixSeams(vec3 vec, float mipmapIndex) {\n"+" float scale = 1.0 - exp2(mipmapIndex) / 64.0;\n"+" float M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n"+" if (abs(vec.x) != M) vec.x *= scale;\n"+" if (abs(vec.y) != M) vec.y *= scale;\n"+" if (abs(vec.z) != M) vec.z *= scale;\n"+" return vec;\n"+"}" return shaderPart;};x3dom.shader.shadowRendering=function(){var shaderPart="";shaderPart+="float getLightInfluence(float lType, float lShadowIntensity, float lOn, vec3 lLocation, vec3 lDirection, "+"float lCutOffAngle, float lBeamWidth, vec3 lAttenuation, float lRadius, vec3 eyeCoords) {\n"+" if (lOn == 0.0 || lShadowIntensity == 0.0){ return 0.0;\n"+" } else if (lType == 0.0) {\n"+" return 1.0;\n"+" } else {\n"+" float attenuation = 0.0;\n"+" vec3 lightVec = (lLocation - (eyeCoords));\n"+" float distance = length(lightVec);\n"+" lightVec = normalize(lightVec);\n"+" eyeCoords = normalize(-eyeCoords);\n"+" if(lRadius == 0.0 || distance <= lRadius) {\n"+" attenuation = 1.0 / max(lAttenuation.x + lAttenuation.y * distance + lAttenuation.z * (distance * distance), 1.0);\n"+" }\n"+" if (lType == 1.0) return attenuation;\n"+" float spotAngle = acos(max(0.0, dot(-lightVec, normalize(lDirection))));\n"+" if(spotAngle >= lCutOffAngle) return 0.0;\n"+" else if(spotAngle <= lBeamWidth) return attenuation;\n"+" else return attenuation * (spotAngle - lCutOffAngle) / (lBeamWidth - lCutOffAngle);\n"+" }\n"+"}\n";shaderPart+="void getShadowValues(inout vec4 shadowMapValues, inout float viewSampleDepth, in mat4 lightMatrix, in vec4 worldCoords, in sampler2D shadowMap){\n"+" vec4 lightSpaceCoords = lightMatrix*worldCoords;\n"+" vec3 lightSpaceCoordsCart = lightSpaceCoords.xyz / lightSpaceCoords.w;\n"+" vec2 textureCoords = (lightSpaceCoordsCart.xy + 1.0)*0.5;\n"+" viewSampleDepth = lightSpaceCoordsCart.z;\n"+" shadowMapValues = texture2D(shadowMap, textureCoords);\n";if(!x3dom.caps.FP_TEXTURES||x3dom.caps.MOBILE) shaderPart+=" shadowMapValues = vec4(1.0,1.0,unpackDepth(shadowMapValues),1.0);\n";shaderPart+="}\n";shaderPart+="void getShadowValuesPointLight(inout vec4 shadowMapValues, inout float viewSampleDepth, in vec3 lLocation, in vec4 worldCoords, in mat4 lightViewMatrix,"+"in mat4 lMatrix_0, in mat4 lMatrix_1, in mat4 lMatrix_2, in mat4 lMatrix_3, in mat4 lMatrix_4, in mat4 lMatrix_5,"+"in sampler2D shadowMap_0, in sampler2D shadowMap_1, in sampler2D shadowMap_2, in sampler2D shadowMap_3,"+"in sampler2D shadowMap_4, in sampler2D shadowMap_5){\n"+" vec4 transformed = lightViewMatrix * worldCoords;\n"+" vec3 lightVec = normalize(transformed.xyz/transformed.w);\n"+" vec3 lightVecAbs = abs(lightVec);\n"+" float maximum = max(max(lightVecAbs.x, lightVecAbs.y),lightVecAbs.z);\n"+" if (lightVecAbs.x == maximum) {\n"+" if (lightVec.x < 0.0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_3,worldCoords,shadowMap_3);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_1,worldCoords,shadowMap_1);\n"+" }\n"+" else if (lightVecAbs.y == maximum) {\n"+" if (lightVec.y < 0.0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_4,worldCoords,shadowMap_4);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_5,worldCoords,shadowMap_5);\n"+" }\n"+" else if (lightVec.z < 0.0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_0,worldCoords,shadowMap_0);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_2,worldCoords,shadowMap_2);\n"+"}\n";shaderPart+="void getShadowValuesCascaded(inout vec4 shadowMapValues, inout float viewSampleDepth, in vec4 worldCoords, in float eyeDepth, in mat4 lMatrix_0, in mat4 lMatrix_1, in mat4 lMatrix_2,"+"in mat4 lMatrix_3, in mat4 lMatrix_4, in mat4 lMatrix_5, in sampler2D shadowMap_0, in sampler2D shadowMap_1, in sampler2D shadowMap_2,"+"in sampler2D shadowMap_3, in sampler2D shadowMap_4, in sampler2D shadowMap_5, in float split_0, in float split_1, in float split_2, in float split_3, in float split_4){\n"+" if (eyeDepth < split_0) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_0, worldCoords, shadowMap_0);\n"+" else if (eyeDepth < split_1) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_1, worldCoords, shadowMap_1);\n"+" else if (eyeDepth < split_2) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_2, worldCoords, shadowMap_2);\n"+" else if (eyeDepth < split_3) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_3, worldCoords, shadowMap_3);\n"+" else if (eyeDepth < split_4) getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_4, worldCoords, shadowMap_4);\n"+" else getShadowValues(shadowMapValues, viewSampleDepth, lMatrix_5, worldCoords, shadowMap_5);\n"+"}\n";shaderPart+="float ESM(float shadowMapDepth, float viewSampleDepth, float offset){\n";if(!x3dom.caps.FP_TEXTURES||x3dom.caps.MOBILE) shaderPart+=" return exp(-80.0*(1.0-offset)*(viewSampleDepth - shadowMapDepth));\n";else shaderPart+=" return shadowMapDepth * exp(-80.0*(1.0-offset)*viewSampleDepth);\n";shaderPart+="}\n";shaderPart+="float VSM(vec2 moments, float viewSampleDepth, float offset){\n"+" viewSampleDepth = (viewSampleDepth + 1.0) * 0.5;\n"+" if (viewSampleDepth <= moments.x) return 1.0;\n"+" float variance = moments.y - moments.x * moments.x;\n"+" variance = max(variance, 0.00002 + offset*0.01);\n"+" float d = viewSampleDepth - moments.x;\n"+" return variance/(variance + d*d);\n"+"}\n";return shaderPart;};x3dom.shader.light=function(numLights){var shaderPart="";for(var l=0;l= lCutOffAngle) spot = 0.0;\n"+" else if(spotAngle <= lBeamWidth) spot = 1.0;\n"+" else spot = (spotAngle - lCutOffAngle ) / (lBeamWidth - lCutOffAngle);\n"+" }\n"+" }\n"+" vec3 H = normalize( L + V );\n"+" float NdotL = clamp(dot(L, N), 0.0, 1.0);\n"+" float NdotH = clamp(dot(H, N), 0.0, 1.0);\n"+" float ambientFactor = lAmbientIntensity * ambIntensity;\n"+" float diffuseFactor = lIntensity * NdotL;\n"+" float specularFactor = lIntensity * pow(NdotH, shin*128.0);\n"+" ambient += lColor * ambientFactor * attentuation * spot;\n"+" diffuse += lColor * diffuseFactor * attentuation * spot;\n"+" specular += lColor * specularFactor * attentuation * spot;\n"+"}\n";return shaderPart;};x3dom.shader.lightPBR=function(numLights){var shaderPart="";for(var l=0;l= lCutOffAngle) spot = 0.0;\n"+" else if(spotAngle <= lBeamWidth) spot = 1.0;\n"+" else spot = (spotAngle - lCutOffAngle ) / (lBeamWidth - lCutOffAngle);\n"+" }\n"+" }\n"+" vec3 fresnel = vec3(1.0, 1.0, 1.0);\n"+" vec3 H = normalize( L + V );\n"+" float NoL = clamp( dot( N, L ), 0.0, 1.0 );\n"+" float NoH = clamp( dot( N, H ), 0.0, 1.0 );\n"+" float NoV = clamp( dot( N, V ), 0.0, 1.0 );\n"+" float VoH = clamp( dot( V, H ), 0.0, 1.0 );\n"+" float ambientFactor = lAmbientIntensity * ambIntensity;\n"+" float diffuseFactor = lIntensity * NoL;\n"+" float spec = lIntensity * NoL;\n"+" float roughness = 1.0 - shin;\n"+" float a = max( roughness * roughness, 5e-4 );\n"+" float a2 = a * a;\n"+" float denom = NoH * NoH * ( a2 - 1.0 ) + 1.0;\n"+" float D = a2 / ( denom * denom );\n"+" float k = a / 2.0;\n"+" float G_V = ( NoV * ( 1.0 - k ) + k );\n"+" float G_L = ( NoL * ( 1.0 - k ) + k );\n"+" float G = 0.25 / ( G_V * G_L );\n"+" vec3 F = reflectivity + (fresnel - fresnel*reflectivity) * exp2( (-5.55473 * VoH - 6.98316) * VoH );\n"+" vec3 specularFactor = (D * G) * (F * spec);\n"+" ambient += lColor * ambientFactor * attentuation * spot;\n"+" diffuse += lColor * diffuseFactor * attentuation * spot;\n"+" specular += lColor * specularFactor * attentuation * spot;\n"+"}\n";return shaderPart;};x3dom.shader.TBNCalculation=function(){var shaderPart="";shaderPart+="mat3 cotangent_frame(vec3 N, vec3 p, vec2 uv)\n"+"{\n"+" // get edge vectors of the pixel triangle\n"+" vec3 dp1 = dFdx( p );\n"+" vec3 dp2 = dFdy( p );\n"+" vec2 duv1 = dFdx( uv );\n"+" vec2 duv2 = dFdy( uv );\n"+"\n"+" // solve the linear system\n"+" vec3 dp2perp = cross( dp2, N );\n"+" vec3 dp1perp = cross( N, dp1 );\n"+" vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n"+" vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n"+"\n"+" // construct a scale-invariant frame\n"+" float invmax = inversesqrt( max( dot(T,T), dot(B,B) ) );\n"+" return mat3( T * invmax, B * invmax, N );\n"+"}\n\n";shaderPart+="vec3 perturb_normal( vec3 N, vec3 V, vec2 texcoord, vec3 bias )\n"+"{\n"+" // assume N, the interpolated vertex normal and\n"+" // V, the view vector (vertex to eye)\n"+" vec3 map = texture2D(normalMap, texcoord ).xyz;\n"+" map = 2.0 * map - 1.0;\n"+" map = map * bias;\n"+" mat3 TBN = cotangent_frame(N, -V, texcoord);\n"+" return normalize(TBN * map);\n"+"}\n\n";return shaderPart;};x3dom.shader.toneMapping=function(){var shaderPart="";shaderPart+="uniform float tonemappingOperator;\n";shaderPart+="vec3 tonemapReinhard(vec3 color) { \n"+" return color / (color + vec3(1.0));\n"+"}\n\n";shaderPart+="vec3 uncharted2Tonemap(vec3 color) { \n"+" float A = 0.15;\n"+" float B = 0.50;\n"+" float C = 0.10;\n"+" float D = 0.20;\n"+" float E = 0.02;\n"+" float F = 0.30;\n"+" return ((color*(A*color+C*B)+D*E)/(color*(A*color+B)+D*F))-E/F;\n"+"}\n\n";shaderPart+="vec3 tonemapUncharted2(vec3 color) { \n"+" float W = 11.2;\n"+" float exposureBias = 2.0;\n"+" vec3 curr = uncharted2Tonemap(exposureBias * color);\n"+" vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W));\n"+" return curr * whiteScale;\n"+"}\n\n";shaderPart+="vec3 tonemapeFilmic(vec3 color) { \n"+" const float a = 2.51;\n"+" const float b = 0.03;\n"+" const float c = 2.43;\n"+" const float d = 0.59;\n"+" const float e = 0.14;\n"+" return clamp((color * (a * color + b)) / (color * (c * color + d ) + e), 0.0, 1.0);\n"+"}\n\n";shaderPart+="vec3 tonemap(vec3 color) { \n"+" if(tonemappingOperator == 0.0) {\n"+" return color;\n"+" }\n"+" if(tonemappingOperator == 1.0) {\n"+" return tonemapReinhard(color);\n"+" }\n"+" if(tonemappingOperator == 2.0) {\n"+" return tonemapUncharted2(color);\n"+" }\n"+" if(tonemappingOperator == 3.0) {\n"+" return tonemapeFilmic(color);\n"+" }\n"+"}\n\n";return shaderPart;};x3dom.shader.DynamicShader=function(gl,properties) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl,properties,x3dom.caps.WEBGL_VERSION);var fragmentShader=this.generateFragmentShader(gl,properties,x3dom.caps.WEBGL_VERSION);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.DynamicShader.prototype.generateVertexShader=function(gl,properties,version) {var shader="";shader+="uniform mat4 modelMatrix;\n";shader+="uniform mat4 modelViewMatrix;\n";shader+="uniform mat4 modelViewProjectionMatrix;\n";shader+="uniform mat4 modelViewMatrix2;\n";shader+="uniform mat4 modelViewProjectionMatrix2;\n";shader+="uniform float isVR;\n";shader+="attribute float eyeIdx;\n";shader+="varying float vrOffset;\n";shader+="varying float fragEyeIdx;\n";if(properties.POSCOMPONENTS==3){shader+="attribute vec3 position;\n";}else if(properties.POSCOMPONENTS==4){shader+="attribute vec4 position;\n";} if(properties.IMAGEGEOMETRY){shader+="uniform vec3 IG_bboxMin;\n";shader+="uniform vec3 IG_bboxMax;\n";shader+="uniform float IG_coordTextureWidth;\n";shader+="uniform float IG_coordTextureHeight;\n";shader+="uniform vec2 IG_implicitMeshSize;\n";for(var i=0;i= 0.0) ? val : -1.0 * val);\n"+"}"+"\n"+"void main(void) {\n"+" gl_FragColor = textureCube(tex, fragNormal);\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundCubeTextureShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.BackgroundCubeTextureDDSShader=function(gl) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);if(!gl.getProgramParameter(this.program,gl.LINK_STATUS)){throw("Error linking shaders:"+gl.getProgramInfoLog(this.program));} return this.program;};x3dom.shader.BackgroundCubeTextureDDSShader.prototype.generateVertexShader=function(gl) {var shader="attribute vec3 position;\n"+"uniform mat4 modelViewProjectionMatrix;\n"+"uniform mat4 modelViewProjectionMatrix2;\n"+"varying vec3 fragNormal;\n"+"uniform float isVR;\n"+"attribute float eyeIdx;\n"+"varying float vrOffset;\n"+"varying float fragEyeIdx;\n"+"\n"+"void main(void) {\n"+" fragEyeIdx = eyeIdx;\n"+" fragNormal = normalize(position);\n"+" if(eyeIdx == 1.0){\n"+" gl_Position = modelViewProjectionMatrix2 * vec4(position, 1.0);\n"+" } else {\n"+" gl_Position = modelViewProjectionMatrix * vec4(position, 1.0);\n"+" }\n"+" if(isVR == 1.0){\n"+" vrOffset = eyeIdx * 0.5;\n"+" gl_Position.x *= 0.5;\n"+" gl_Position.x += vrOffset * gl_Position.w;\n"+" }\n"+"}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundCubeTextureShader] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.BackgroundCubeTextureDDSShader.prototype.generateFragmentShader=function(gl) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+=x3dom.shader.toneMapping();shader+=x3dom.shader.gammaCorrectionDecl({});shader+="uniform float isVR;\n"+"varying float vrOffset;\n"+"varying float fragEyeIdx;\n"+"uniform float screenWidth;\n"+"uniform samplerCube tex;\n"+"varying vec3 fragNormal;\n"+"\n"+"void main(void) {\n"+" if ( isVR == 1.0 ) {\n"+" if ( ( step( 0.5, gl_FragCoord.x / screenWidth ) - 0.5 ) * vrOffset < 0.0 ) discard;\n"+" }\n"+" vec4 color = textureCube(tex, fragNormal);\n"+" if(tonemappingOperator == 1.0) {\n"+" color.rgb = tonemapReinhard(color.rgb);\n"+" }\n"+" if(tonemappingOperator == 2.0) {\n"+" color.rgb = tonemapUncharted2(color.rgb);\n"+" }\n"+" if(tonemappingOperator == 3.0) {\n"+" color.rgb = tonemapeFilmic(color.rgb);\n"+" }\n"+" color = "+x3dom.shader.encodeGamma({},"color")+";\n"+" gl_FragColor = color;\n"+"}\n";var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,shader);gl.compileShader(fragmentShader);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[BackgroundCubeTextureShader] FragmentShader "+gl.getShaderInfoLog(fragmentShader));} return fragmentShader;};x3dom.shader.ShadowRenderingShader=function(gl,shadowedLights) {this.program=gl.createProgram();var vertexShader=this.generateVertexShader(gl);var fragmentShader=this.generateFragmentShader(gl,shadowedLights);gl.attachShader(this.program,vertexShader);gl.attachShader(this.program,fragmentShader);gl.bindAttribLocation(this.program,0,"position");gl.linkProgram(this.program);return this.program;};x3dom.shader.ShadowRenderingShader.prototype.generateVertexShader=function(gl) {var shader="";shader+="attribute vec2 position;\n";shader+="varying vec2 vPosition;\n";shader+="void main(void) {\n";shader+=" vPosition = position;\n";shader+=" gl_Position = vec4(position, -1.0, 1.0);\n";shader+="}\n";var vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,shader);gl.compileShader(vertexShader);if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){x3dom.debug.logError("[ShadowRendering] VertexShader "+gl.getShaderInfoLog(vertexShader));} return vertexShader;};x3dom.shader.ShadowRenderingShader.prototype.generateFragmentShader=function(gl,shadowedLights) {var shader="#ifdef GL_FRAGMENT_PRECISION_HIGH\n";shader+="precision highp float;\n";shader+="#else\n";shader+=" precision mediump float;\n";shader+="#endif\n\n";shader+="uniform mat4 inverseViewProj;\n";shader+="uniform mat4 inverseProj;\n";shader+="varying vec2 vPosition;\n";shader+="uniform sampler2D sceneMap;\n";for(var i=0;i<5;i++) shader+="uniform float cascade"+i+"_Depth;\n";for(var l=0;l=0||navigator.appVersion.indexOf("Mobile")>-1||x3dom.caps.MAX_VARYING_VECTORS<=8||x3dom.caps.MAX_VERTEX_TEXTURE_IMAGE_UNITS<2){x3dom.caps.MOBILE=true;} x3dom.caps.MOBILE=false;if(isAppleDevice) {x3dom.caps.HFP_TEXTURES=false;} if(isSafariBrowser) {x3dom.caps.TEXTURE_LOD=false;} if(x3dom.caps.MOBILE){if(forbidMobileShaders){x3dom.caps.MOBILE=false;x3dom.debug.logWarning("Detected mobile graphics card! "+"But being forced to desktop shaders which might not work!");}else{x3dom.debug.logWarning("Detected mobile graphics card! "+"Using low quality shaders without ImageGeometry support!");}}else{if(forceMobileShaders){x3dom.caps.MOBILE=true;x3dom.debug.logWarning("Detected desktop graphics card! "+"But being forced to mobile shaders with lower quality!");}}}catch(ex){x3dom.debug.logWarning("Your browser probably supports an older WebGL version. "+"Please try the old mobile runtime instead:\n"+"http://www.x3dom.org/x3dom/src_mobile/x3dom.js");newCtx=null;} return newCtx;}}catch(e){x3dom.debug.logWarning(e);}} return null;} Context.prototype.setupShape=function(gl,drawable,viewarea){var q=0,q6;var textures,t;var vertices,positionBuffer;var texCoords,texCoordBuffer;var tangents,tangentBuffer;var binormals,binormalBuffer;var indicesBuffer,indexArray;var normals,normalBuffer;var colors,colorBuffer;var shape=drawable.shape;var geoNode=shape._cf.geometry.node;if(shape._webgl!==undefined){var needFullReInit=false;if(shape._dirty.colors===true&&shape._webgl.shader.color===undefined&&geoNode._mesh._colors[0].length){needFullReInit=true;} if(needFullReInit&&shape._cleanupGLObjects){shape._cleanupGLObjects(true,false);} if(shape._dirty.texture===true){if(shape._webgl.texture.length!=shape.getTextures().length){for(t=0;t65535)){indexArray=new Uint32Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_INT;}else{indexArray=new Uint16Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_SHORT;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indicesBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.STATIC_DRAW);indexArray=null;shape._webgl.positions[q]=geoNode._mesh._positions[q];gl.deleteBuffer(shape._webgl.buffers[q6+x3dom.BUFFER_IDX.POSITION]);positionBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.POSITION]=positionBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,shape._webgl.buffers[q6+x3dom.BUFFER_IDX.INDEX]);vertices=new Float32Array(shape._webgl.positions[q]);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.vertexAttribPointer(shape._webgl.shader.position,geoNode._mesh._numPosComponents,shape._webgl.coordType,false,shape._coordStrideOffset[0],shape._coordStrideOffset[1]);vertices=null;} shape._dirty.positions=false;shape._dirty.indexes=false;} if(shape._dirty.colors==true){if(shape._webgl.shader.color!==undefined){shape._webgl.colors[q]=geoNode._mesh._colors[q];gl.deleteBuffer(shape._webgl.buffers[q6+x3dom.BUFFER_IDX.COLOR]);colorBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.COLOR]=colorBuffer;colors=new Float32Array(shape._webgl.colors[q]);gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW);gl.vertexAttribPointer(shape._webgl.shader.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);colors=null;} shape._dirty.colors=false;} if(shape._dirty.normals==true){if(shape._webgl.shader.normal!==undefined){shape._webgl.normals[q]=geoNode._mesh._normals[q];gl.deleteBuffer(shape._webgl.buffers[q6+x3dom.BUFFER_IDX.NORMAL]);normalBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.NORMAL]=normalBuffer;normals=new Float32Array(shape._webgl.normals[q]);gl.bindBuffer(gl.ARRAY_BUFFER,normalBuffer);gl.bufferData(gl.ARRAY_BUFFER,normals,gl.STATIC_DRAW);gl.vertexAttribPointer(shape._webgl.shader.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);normals=null;} shape._dirty.normals=false;} if(shape._dirty.texcoords==true){if(shape._webgl.shader.texcoord!==undefined){shape._webgl.texcoords[q]=geoNode._mesh._texCoords[q];gl.deleteBuffer(shape._webgl.buffers[q6+x3dom.BUFFER_IDX.TEXCOORD]);texCoordBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.TEXCOORD]=texCoordBuffer;texCoords=new Float32Array(shape._webgl.texcoords[q]);gl.bindBuffer(gl.ARRAY_BUFFER,texCoordBuffer);gl.bufferData(gl.ARRAY_BUFFER,texCoords,gl.STATIC_DRAW);gl.vertexAttribPointer(shape._webgl.shader.texCoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);texCoords=null;} shape._dirty.texcoords=false;} if(shape._dirty.specialAttribs==true){if(shape._webgl.shader.particleSize!==undefined){var szArr=geoNode._vf.size.toGL();if(szArr.length){gl.deleteBuffer(shape._webgl.buffers[q6+x3dom.BUFFER_IDX.ID]);shape._webgl.buffers[q6+x3dom.BUFFER_IDX.ID]=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,shape._webgl.buffers[q6+x3dom.BUFFER_IDX.ID]);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(szArr),gl.STATIC_DRAW);} shape._dirty.specialAttribs=false;}}}}else{} if(shape._webgl.imageGeometry!=0){for(t=0;t0&&force)||this._parentNodes.length==0)){var sp=this._webgl.shader;for(var q=0;q65535)){indexArray=new Uint32Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_INT;}else{indexArray=new Uint16Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_SHORT;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indicesBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.STATIC_DRAW);indexArray=null;positionBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.POSITION]=positionBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);vertices=new Float32Array(shape._webgl.positions[q]);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.vertexAttribPointer(sp.position,geoNode._mesh._numPosComponents,shape._webgl.coordType,false,shape._coordStrideOffset[0],shape._coordStrideOffset[1]);gl.enableVertexAttribArray(sp.position);vertices=null;} if(sp.normal!==undefined||shape._webgl.normals[q]){normalBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.NORMAL]=normalBuffer;var normals=new Float32Array(shape._webgl.normals[q]);gl.bindBuffer(gl.ARRAY_BUFFER,normalBuffer);gl.bufferData(gl.ARRAY_BUFFER,normals,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.normal,geoNode._mesh._numNormComponents,shape._webgl.normalType,false,shape._normalStrideOffset[0],shape._normalStrideOffset[1]);gl.enableVertexAttribArray(sp.normal);normals=null;} if(sp.texcoord!==undefined){var texcBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.TEXCOORD]=texcBuffer;var texCoords=new Float32Array(shape._webgl.texcoords[q]);gl.bindBuffer(gl.ARRAY_BUFFER,texcBuffer);gl.bufferData(gl.ARRAY_BUFFER,texCoords,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.texcoord,geoNode._mesh._numTexComponents,shape._webgl.texCoordType,false,shape._texCoordStrideOffset[0],shape._texCoordStrideOffset[1]);gl.enableVertexAttribArray(sp.texcoord);texCoords=null;} if(sp.color!==undefined){colorBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.COLOR]=colorBuffer;var colors=new Float32Array(shape._webgl.colors[q]);gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.color,geoNode._mesh._numColComponents,shape._webgl.colorType,false,shape._colorStrideOffset[0],shape._colorStrideOffset[1]);gl.enableVertexAttribArray(sp.color);colors=null;} if(sp.particleSize!==undefined){var sizeArr=geoNode._vf.size.toGL();if(sizeArr.length){var sizeBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.ID]=sizeBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,sizeBuffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(sizeArr),gl.STATIC_DRAW);}} if(sp.tangent!==undefined){tangentBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.TANGENT]=tangentBuffer;var tangents=new Float32Array(shape._webgl.tangents[q]);gl.bindBuffer(gl.ARRAY_BUFFER,tangentBuffer);gl.bufferData(gl.ARRAY_BUFFER,tangents,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.tangent,geoNode._mesh._numTangentComponents,shape._webgl.tangentType,false,shape._tangentStrideOffset[0],shape._tangentStrideOffset[1]);gl.enableVertexAttribArray(sp.tangent);tangents=null;} if(sp.binormal!==undefined){binormalBuffer=gl.createBuffer();shape._webgl.buffers[q6+x3dom.BUFFER_IDX.BITANGENT]=binormalBuffer;var binormals=new Float32Array(shape._webgl.binormals[q]);gl.bindBuffer(gl.ARRAY_BUFFER,binormalBuffer);gl.bufferData(gl.ARRAY_BUFFER,binormals,gl.STATIC_DRAW);gl.vertexAttribPointer(sp.binormal,geoNode._mesh._numBinormalComponents,shape._webgl.binormalType,false,shape._binormalStrideOffset[0],shape._binormalStrideOffset[1]);gl.enableVertexAttribArray(sp.tangent);binormals=null;}} for(var df in geoNode._mesh._dynamicFields){if(!geoNode._mesh._dynamicFields.hasOwnProperty(df)) continue;var attrib=geoNode._mesh._dynamicFields[df];shape._webgl.dynamicFields[currAttribs]={buf:{},name:df,numComponents:attrib.numComponents};if(sp[df]!==undefined){var attribBuffer=gl.createBuffer();shape._webgl.dynamicFields[currAttribs++].buf=attribBuffer;var attribs=new Float32Array(attrib.value);gl.bindBuffer(gl.ARRAY_BUFFER,attribBuffer);gl.bufferData(gl.ARRAY_BUFFER,attribs,gl.STATIC_DRAW);gl.vertexAttribPointer(sp[df],attrib.numComponents,gl.FLOAT,false,0,0);attribs=null;}}}};Context.prototype.setupScene=function(gl,bgnd){var sphere=null;var texture=null;var that=this;if(bgnd._webgl!==undefined){if(!bgnd._dirty){return;} if(bgnd._webgl.texture!==undefined&&bgnd._webgl.texture){gl.deleteTexture(bgnd._webgl.texture);} if(bgnd._cleanupGLObjects){bgnd._cleanupGLObjects();} bgnd._webgl={};} bgnd._dirty=false;var url=bgnd.getTexUrl();var i=0;var w=1,h=1;if(url.length>0&&url[0].length>0){if((url.length>=6&&url[1].length>0&&url[2].length>0&&url[3].length>0&&url[4].length>0&&url[5].length>0)||url[0].indexOf(".dds")!=-1){sphere=new x3dom.nodeTypes.Sphere();bgnd._webgl={positions:sphere._mesh._positions[0],indexes:sphere._mesh._indices[0],buffers:[{},{}]};bgnd._webgl.primType=gl.TRIANGLES;if(url[0].indexOf(".dds")!=-1){bgnd._webgl.shader=this.cache.getShader(gl,x3dom.shader.BACKGROUND_CUBETEXTURE_DDS);bgnd._webgl.texture=x3dom.Utils.createTextureCube(gl,bgnd._nameSpace.doc,[url[0]],false,bgnd._vf.crossOrigin,true,false,false);}else{bgnd._webgl.shader=this.cache.getShader(gl,x3dom.shader.BACKGROUND_CUBETEXTURE_DDS);bgnd._webgl.texture=x3dom.Utils.createTextureCube(gl,bgnd._nameSpace.doc,url,false,bgnd._vf.crossOrigin,true,false);}} else{bgnd._webgl={positions:[-w,-h,0,-w,h,0,w,-h,0,w,h,0],indexes:[0,1,2,3],buffers:[{},{}]};url=bgnd._nameSpace.getURL(url[0]);bgnd._webgl.texture=x3dom.Utils.createTexture2D(gl,bgnd._nameSpace.doc,url,true,bgnd._vf.crossOrigin,false,false);bgnd._webgl.primType=gl.TRIANGLE_STRIP;bgnd._webgl.shader=that.cache.getShader(gl,x3dom.shader.BACKGROUND_TEXTURE);}}else{if(bgnd.getSkyColor().length>1||bgnd.getGroundColor().length){sphere=new x3dom.nodeTypes.Sphere();texture=gl.createTexture();bgnd._webgl={positions:sphere._mesh._positions[0],texcoords:sphere._mesh._texCoords[0],indexes:sphere._mesh._indices[0],buffers:[{},{},{}],texture:texture,primType:gl.TRIANGLES};var N=x3dom.Utils.nextHighestPowerOfTwo(bgnd.getSkyColor().length+bgnd.getGroundColor().length+2);N=(N<512)?512:N;var n=bgnd._vf.groundAngle.length;var tmp=[],arr=[];var colors=[],sky=[0];for(i=0;i0||bgnd._vf.groundColor.length==1){if(sky[sky.length-1]=0;i--){if((i==n-1)&&(Math.PI-bgnd._vf.groundAngle[i]<=Math.PI/2)){sky[sky.length]=Math.PI/2;colors[colors.length]=bgnd._vf.groundColor[bgnd._vf.groundColor.length-1];} sky[sky.length]=Math.PI-bgnd._vf.groundAngle[i];colors[colors.length]=bgnd._vf.groundColor[i+1];} if(n==0&&bgnd._vf.groundColor.length==1){sky[sky.length]=Math.PI/2;colors[colors.length]=bgnd._vf.groundColor[0];} sky[sky.length]=Math.PI;colors[colors.length]=bgnd._vf.groundColor[0];}else{if(sky[sky.length-1]viewport.y){ratio=viewport.x/texture.x;texture.x=viewport.x;texture.y=texture.y*ratio;}else{ratio=viewport.y/texture.y;texture.y=viewport.y;texture.x=texture.x*ratio;} var scale=viewport.divideComponents(texture);var translation=texture.subtract(viewport).multiply(0.5).divideComponents(texture);}else{var scale=new x3dom.fields.SFVec2f(1.0,1.0);var translation=new x3dom.fields.SFVec2f(0.0,0.0);} sp.scale=scale.toGL();sp.translation=translation.toGL();} sp.isVR=-1.0;sp.screenWidth=that.canvas.width;that.setTonemappingOperator(viewarea,sp);if(that.VRMode==2) {var mat_view_R=viewarea.getViewMatrices()[1];var camPosR=mat_view_R.e3();mat_view_R._03=0;mat_view_R._13=0;mat_view_R._23=0;var mat_proj_R=viewarea.getProjectionMatrices()[1];var mat_scene_R=mat_proj_R.mult(mat_view_R);sp.modelViewProjectionMatrix2=mat_scene_R.toGL();mat_view_R._03=camPosR.x;mat_view_R._13=camPosR.y;mat_view_R._23=camPosR.z;sp.isVR=1.0;} that.setVertexAttribEyeIdx(gl,sp);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,bgnd._webgl.buffers[x3dom.BUFFER_IDX.INDEX]);gl.bindBuffer(gl.ARRAY_BUFFER,bgnd._webgl.buffers[x3dom.BUFFER_IDX.POSITION]);gl.vertexAttribPointer(sp.position,3,gl.FLOAT,false,0,0);gl.enableVertexAttribArray(sp.position);that.drawElements(gl,bgnd._webgl.primType,bgnd._webgl.indexes.length,gl.UNSIGNED_SHORT,0);gl.disableVertexAttribArray(sp.position);that.disableVertexAttribEyeIdx(gl,sp);gl.activeTexture(gl.TEXTURE0);if(bgnd._webgl.texture.textureCubeReady){gl.bindTexture(gl.TEXTURE_CUBE_MAP,null);}else{gl.bindTexture(gl.TEXTURE_2D,null);} gl.clear(gl.DEPTH_BUFFER_BIT);}};};Context.prototype.setupFgnds=function(gl,scene){if(scene._fgnd!==undefined){return;} var that=this;var w=1,h=1;scene._fgnd={};scene._fgnd._webgl={positions:[-w,-h,0,-w,h,0,w,-h,0,w,h,0],indexes:[0,1,2,3],buffers:[{},{}]};scene._fgnd._webgl.primType=gl.TRIANGLE_STRIP;scene._fgnd._webgl.shader=this.cache.getShader(gl,x3dom.shader.FRONTGROUND_TEXTURE);var sp=scene._fgnd._webgl.shader;var positionBuffer=gl.createBuffer();scene._fgnd._webgl.buffers[x3dom.BUFFER_IDX.POSITION]=positionBuffer;gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);var vertices=new Float32Array(scene._fgnd._webgl.positions);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);gl.vertexAttribPointer(sp.position,3,gl.FLOAT,false,0,0);var indicesBuffer=gl.createBuffer();scene._fgnd._webgl.buffers[x3dom.BUFFER_IDX.INDEX]=indicesBuffer;var indexArray=new Uint16Array(scene._fgnd._webgl.indexes);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indicesBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.STATIC_DRAW);vertices=null;indexArray=null;scene._fgnd._webgl.render=function(gl,tex){scene._fgnd._webgl.texture=tex;that.stateManager.frontFace(gl.CCW);that.stateManager.disable(gl.CULL_FACE);that.stateManager.disable(gl.DEPTH_TEST);that.stateManager.useProgram(sp);if(!sp.tex){sp.tex=0;} gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,scene._fgnd._webgl.texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,scene._fgnd._webgl.buffers[x3dom.BUFFER_IDX.INDEX]);gl.bindBuffer(gl.ARRAY_BUFFER,scene._fgnd._webgl.buffers[x3dom.BUFFER_IDX.POSITION]);gl.vertexAttribPointer(sp.position,3,gl.FLOAT,false,0,0);gl.enableVertexAttribArray(sp.position);that.drawElements(gl,scene._fgnd._webgl.primType,scene._fgnd._webgl.indexes.length,gl.UNSIGNED_SHORT,0,1);gl.disableVertexAttribArray(sp.position);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,null);};};Context.prototype.renderShadowPass=function(gl,viewarea,mat_scene,mat_view,targetFbo,camOffset,isCameraView){var scene=viewarea._scene;var indicesReady=false;this.stateManager.bindFramebuffer(gl.FRAMEBUFFER,targetFbo.fbo);this.stateManager.viewport(0,0,targetFbo.width,targetFbo.height);gl.clearColor(1.0,1.0,1.0,0.0);gl.clearDepth(1.0);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this.stateManager.depthFunc(gl.LEQUAL);this.stateManager.enable(gl.DEPTH_TEST);this.stateManager.enable(gl.CULL_FACE);this.stateManager.disable(gl.BLEND);var bgCenter=x3dom.fields.SFVec3f.NullVector.toGL();var bgSize=x3dom.fields.SFVec3f.OneVector.toGL();var env=scene.getEnvironment();var excludeTrans=env._vf.shadowExcludeTransparentObjects;var i,n=scene.drawableCollection.length;for(i=0;i0||s_gl.popGeometry>0)){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v>>8)/255.0;sp.from=from.toGL();sp.sceneSize=sceneSize;if((s_gl.binaryGeometry!=0||s_gl.externalGeometry!=0)&&s_geo._vf["idsPerVertex"]==true){sp.shadowIDs=(shape._vf.idOffset+x3dom.nodeTypes.Shape.objectID+2);} if(s_gl.coordType!=gl.FLOAT){if(!s_gl.popGeometry&&(x3dom.Utils.isUnsignedType(s_geo._vf.coordType))){sp.bgCenter=s_geo.getMin().toGL();}else{sp.bgCenter=s_geo._vf.position.toGL();} sp.bgSize=s_geo._vf.size.toGL();sp.bgPrecisionMax=s_geo.getPrecisionMax('coordType');} if(pickMode==1&&s_gl.colorType!=gl.FLOAT){sp.bgPrecisionColMax=s_geo.getPrecisionMax('colorType');} if(pickMode==2&&s_gl.texCoordType!=gl.FLOAT){sp.bgPrecisionTexMax=s_geo.getPrecisionMax('texCoordType');} if(shape._clipPlanes){sp.modelViewMatrix=mat_view.mult(trafo).toGL();sp.viewMatrixInverse=mat_view.inverse().toGL();if(this.VRMode==2) {sp.modelViewMatrix2=mat_view_R.mult(trafo).toGL();sp.viewMatrixInverse2=mat_view_R.inverse().toGL();} for(var cp=0;cp0||s_gl.popGeometry>0)){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v0)){this.drawElements(gl,s_gl.primType[0],s_geo._vf.vertexCount[0],s_gl.indexType,shape._indexOffset);}else if(s_gl.bufferGeometry<0){this.drawArrays(gl,s_gl.primType[0],0,s_geo._vf.vertexCount[0]);}else if(s_geo.hasIndexOffset()){var indOff=shape.tessellationProperties();for(v=0,v_n=indOff.length;v0) polyMode=(renderMode==1)?gl.POINTS:gl.LINES;mesh.render(gl,polyMode);}else if(!(sp.position!==undefined&&s_gl.buffers[q6+x3dom.BUFFER_IDX.POSITION]&&s_gl.indexes[q])){continue;}else{indicesReady=false;if(!(sp.position!==undefined&&s_gl.buffers[q6+x3dom.BUFFER_IDX.POSITION]&&(s_gl.indexes[q]))) continue;if(s_gl.buffers[q6+x3dom.BUFFER_IDX.INDEX]){if(isParticleSet&&s_geo.drawOrder()!="any"){var indexArray,zPos=[];var pnts=s_geo._cf.coord.node.getPoints();var pn=(pnts.length==s_gl.indexes[q].length)?s_gl.indexes[q].length:0;for(var i=0;i65535)){indexArray=new Uint32Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_INT;}else{indexArray=new Uint16Array(shape._webgl.indexes[q]);shape._webgl.indexType=gl.UNSIGNED_SHORT;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,s_gl.buffers[q6+x3dom.BUFFER_IDX.INDEX]);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indexArray,gl.DYNAMIC_DRAW);indexArray=null;} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,s_gl.buffers[q6+x3dom.BUFFER_IDX.INDEX]);indicesReady=true;} this.setVertexAttribEyeIdx(gl,sp);this.setVertexAttribPointerPosition(gl,shape,q6,q);this.setVertexAttribPointerNormal(gl,shape,q6,q);this.setVertexAttribPointerTexCoord(gl,shape,q6,q);this.setVertexAttribPointerTexCoord2(gl,shape,q6,q);this.setVertexAttribPointerColor(gl,shape,q6,q);this.setVertexAttribPointerTangent(gl,shape,q6,q);this.setVertexAttribPointerBinormal(gl,shape,q6,q);if((sp.id!==undefined||sp.particleSize!==undefined)&&shape._webgl.buffers[q6+x3dom.BUFFER_IDX.ID]){gl.bindBuffer(gl.ARRAY_BUFFER,shape._webgl.buffers[q6+x3dom.BUFFER_IDX.ID]);if((s_gl.binaryGeometry!=0||s_gl.externalGeometry!=0)&&s_geo._vf["idsPerVertex"]==true){gl.vertexAttribPointer(sp.id,1,gl.FLOAT,false,4,0);gl.enableVertexAttribArray(sp.id);}else if(isParticleSet){gl.vertexAttribPointer(sp.particleSize,3,gl.FLOAT,false,0,0);gl.enableVertexAttribArray(sp.particleSize);}} if(s_gl.popGeometry!=0&&s_gl.buffers[q6+x3dom.BUFFER_IDX.ID]){gl.bindBuffer(gl.ARRAY_BUFFER,s_gl.buffers[q6+x3dom.BUFFER_IDX.ID]);gl.vertexAttribPointer(sp.PG_vertexID,1,gl.FLOAT,false,4,0);gl.enableVertexAttribArray(sp.PG_vertexID);} var indOff,renderMode=viewarea.getRenderMode();if(renderMode>0){var polyMode=(renderMode==1)?gl.POINTS:gl.LINES;if(indicesReady&&(s_gl.binaryGeometry>0||s_gl.popGeometry>0)){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v0)){this.drawElements(gl,s_gl.primType[0],s_geo._vf.vertexCount[0],s_gl.indexType,shape._indexOffset);}else if(s_gl.bufferGeometry<0){this.drawArrays(gl,s_gl.primType[0],0,s_geo._vf.vertexCount[0]);}else if(s_geo.hasIndexOffset()){indOff=shape.tessellationProperties();for(v=0,v_n=indOff.length;v0||s_gl.popGeometry>0)){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v0)){this.drawElements(gl,s_gl.primType[0],s_geo._vf.vertexCount[0],s_gl.indexType,shape._indexOffset);}else if(s_gl.bufferGeometry<0){this.drawArrays(gl,s_gl.primType[0],0,s_geo._vf.vertexCount[0]);}else if(s_geo.hasIndexOffset()){indOff=shape.tessellationProperties();for(v=0,v_n=indOff.length;v0){var viewpoint=scene.getViewpoint();var imgPlaneHeightAtDistOne=viewpoint.getImgPlaneHeightAtDistOne();var near=viewpoint.getNear();var center=model_view.multMatrixPnt(popGeo._vf.position);var tightRad=model_view.multMatrixVec(popGeo._vf.size).length()*0.5;var largestRad=model_view.multMatrixVec(popGeo._vf.maxBBSize).length()*0.5;var dist=Math.max(-center.z-tightRad,near);var projPixelLength=dist*(imgPlaneHeightAtDistOne/viewarea._height);var arg=(2*largestRad)/(tol*projPixelLength);currentLOD=Math.ceil(Math.log(arg)/0.693147180559945);currentLOD=(currentLOD<1)?1:((currentLOD>16)?16:currentLOD);} var minPrec=popGeo._vf.minPrecisionLevel,maxPrec=popGeo._vf.maxPrecisionLevel;currentLOD=(minPrec!=-1&¤tLODmaxPrec)?maxPrec:currentLOD;var currentLOD_min=(s_gl.levelsAvailable4){mat_view=viewMat;mat_scene=sceneMat;}else{mat_view=viewarea._last_mat_view;mat_scene=viewarea._last_mat_scene;} var min=x3dom.fields.SFVec3f.copy(scene._lastMin);var max=x3dom.fields.SFVec3f.copy(scene._lastMax);var from=mat_view.inverse().e3();var _min=x3dom.fields.SFVec3f.copy(from);var _max=x3dom.fields.SFVec3f.copy(from);if(_min.x>min.x){_min.x=min.x;} if(_min.y>min.y){_min.y=min.y;} if(_min.z>min.z){_min.z=min.z;} if(_max.x0&&shapeId>>8,buttonState&255);if(objId>=baseID){objId-=baseID;var hitObject;var layerX=x*viewarea._inverseDevicePixelRatio;var layerY=y*viewarea._inverseDevicePixelRatio;if(pickMode!=4){viewarea._pickingInfo.pickPos=pickPos;viewarea._pick.setValues(pickPos);viewarea._pickingInfo.pickNorm=pickNorm;viewarea._pickNorm.setValues(pickNorm);viewarea._pickingInfo.pickObj=null;viewarea._pickingInfo.lastClickObj=null;hitObject=scene._xmlNode;}else{viewarea._pickingInfo.pickObj=x3dom.nodeTypes.Shape.idMap.nodeID[shapeId];hitObject=viewarea._pickingInfo.pickObj._xmlNode;} if(scene._multiPartMap){var mp,multiPart;for(mp=0;mp=multiPart._minId&&objId<=multiPart._maxId){hitObject=multiPart._xmlNode;event={target:multiPart._xmlNode,button:button,mouseup:((buttonState>>>8)>0),layerX:layerX,layerY:layerY,pickedId:objId,worldX:pickPos.x,worldY:pickPos.y,worldZ:pickPos.z,normalX:pickNorm.x,normalY:pickNorm.y,normalZ:pickNorm.z,hitPnt:pickPos.toGL(),hitObject:hitObject,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};multiPart.handleEvents(event);}else{event={target:multiPart._xmlNode,button:button,mouseup:((buttonState>>>8)>0),layerX:layerX,layerY:layerY,pickedId:-1,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};multiPart.handleEvents(event);}}} shadowObjectIdChanged=(viewarea._pickingInfo.shadowObjectId!=objId);viewarea._pickingInfo.lastShadowObjectId=viewarea._pickingInfo.shadowObjectId;viewarea._pickingInfo.shadowObjectId=objId;if((shadowObjectIdChanged||button)&&scene._xmlNode&&(scene._xmlNode["on"+eventType]||scene._xmlNode.hasAttribute("on"+eventType)||scene._listeners[eventType])){event={target:scene._xmlNode,type:eventType,button:button,mouseup:((buttonState>>>8)>0),layerX:layerX,layerY:layerY,shadowObjectId:objId,worldX:pickPos.x,worldY:pickPos.y,worldZ:pickPos.z,normalX:pickNorm.x,normalY:pickNorm.y,normalZ:pickNorm.z,hitPnt:pickPos.toGL(),hitObject:hitObject,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};scene.callEvtHandler(("on"+eventType),event);} if(scene._shadowIdMap&&scene._shadowIdMap.mapping&&objId>>8)>0),layerX:layerX,layerY:layerY,pickedId:-1,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};multiPart.handleEvents(event);}} shadowObjectIdChanged=(viewarea._pickingInfo.shadowObjectId!=-1);viewarea._pickingInfo.shadowObjectId=-1;if(shadowObjectIdChanged&&scene._xmlNode&&(scene._xmlNode["on"+eventType]||scene._xmlNode.hasAttribute("on"+eventType)||scene._listeners[eventType])){event={target:scene._xmlNode,type:eventType,button:button,mouseup:((buttonState>>>8)>0),layerX:layerX,layerY:layerY,shadowObjectId:viewarea._pickingInfo.shadowObjectId,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};scene.callEvtHandler(("on"+eventType),event);} if(objId>0){viewarea._pickingInfo.pickPos=pickPos;viewarea._pickingInfo.pickNorm=pickNorm;viewarea._pickingInfo.pickObj=x3dom.nodeTypes.Shape.idMap.nodeID[objId];}else{viewarea._pickingInfo.pickObj=null;viewarea._pickingInfo.lastClickObj=null;}}} var pickTime=x3dom.Utils.stopMeasure("picking");this.x3dElem.runtime.addMeasurement('PICKING',pickTime);return true;};Context.prototype.pickRect=function(viewarea,x1,y1,x2,y2,fromMultipartAPI){var gl=this.ctx3d;var scene=viewarea?viewarea._scene:null;fromMultipartAPI=(fromMultipartAPI!=undefined)?fromMultipartAPI:false;if(!gl||!scene||!scene._webgl||!scene.drawableCollection) return false;var from=viewarea._last_mat_view.inverse().e3();var sceneSize=scene._lastMax.subtract(scene._lastMin).length();var x=(x1<=x2)?x1:x2;var y=(y1>=y2)?y1:y2;var width=(1+Math.abs(x2-x1))*scene._webgl.pickScale;var height=(1+Math.abs(y2-y1))*scene._webgl.pickScale;this.renderPickingPass(gl,scene,viewarea._last_mat_view,viewarea._last_mat_scene,from,sceneSize,0,x,y,(width<1)?1:width,(height<1)?1:height);var index;var pickedObjects=[];for(index=0;scene._webgl.fboPick.pixelData&&index0) pickedObjects.push(objId);} pickedObjects.sort();var pickedObjectsTemp=(function(arr){var a=[],l=arr.length;for(var i=0;i=baseID){objId-=baseID;if(scene._multiPartMap){var mp,multiPart,colorMap,emissiveMap,specularMap,visibilityMap,partID;for(mp=0;mp=multiPart._minId&&objId<=multiPart._maxId){partIDs.push(objId);partID=multiPart._idMap.mapping[objId-multiPart._minId].name;hitObject=new x3dom.Parts(multiPart,[objId],colorMap,emissiveMap,specularMap,visibilityMap);pickedNode={"partID":partID,"part":hitObject};pickedNodes.push(pickedNode);}}}}else{hitObject=x3dom.nodeTypes.Shape.idMap.nodeID[objId];hitObject=(hitObject&&hitObject._xmlNode)?hitObject._xmlNode:null;if(hitObject) pickedNodes.push(hitObject);}} if(fromMultipartAPI&&partIDs.length){pickedNodes=new x3dom.Parts(multiPart,partIDs,colorMap,emissiveMap,specularMap,visibilityMap);} return pickedNodes;};Context.prototype.renderScene=function(viewarea,vrFrameData) {var gl=this.ctx3d;var scene=viewarea._scene;if(gl===null||scene===null){return;} var rentex=viewarea._doc._nodeBag.renderTextures;var rt_tex,rtl_i,rtl_n=rentex.length;var texProp=null;var type=gl.UNSIGNED_BYTE;var shadowType=gl.UNSIGNED_BYTE;var nearestFilt=false;if(x3dom.caps.FP_TEXTURES&&!x3dom.caps.MOBILE){type=gl.FLOAT;shadowType=gl.FLOAT;if(!x3dom.caps.FPL_TEXTURES){nearestFilt=true;}} var shadowedLights,numShadowMaps;var i,j,n,size,sizeAvailable;var texType,refinementPos;var vertices=[-1,-1,1,-1,-1,1,-1,1,1,-1,1,1];scene.updateVolume();if(!scene._webgl){scene._webgl={};this.setupFgnds(gl,scene);scene._webgl.pickScale=0.5;scene._webgl._currFboWidth=Math.round(this.canvas.width*scene._webgl.pickScale);scene._webgl._currFboHeight=Math.round(this.canvas.height*scene._webgl.pickScale);scene._webgl.fboPick=x3dom.Utils.initFBO(gl,scene._webgl._currFboWidth,scene._webgl._currFboHeight,gl.UNSIGNED_BYTE,false,true);scene._webgl.fboPick.pixelData=null;scene._webgl.normalShader=this.cache.getShader(gl,x3dom.shader.NORMAL);scene._webgl.fboShadow=[];shadowedLights=viewarea.getShadowedLights();n=shadowedLights.length;for(i=0;i0||x3dom.SSAO.isEnabled(scene)) scene._webgl.fboScene=x3dom.Utils.initFBO(gl,this.canvas.width,this.canvas.height,shadowType,false,true);scene._webgl.fboBlur=[];for(i=0;i0)&&typeof scene._webgl.fboScene=="undefined"||scene._webgl.fboScene&&(this.canvas.width!=scene._webgl.fboScene.width||this.canvas.height!=scene._webgl.fboScene.height)){scene._webgl.fboScene=x3dom.Utils.initFBO(gl,this.canvas.width,this.canvas.height,shadowType,false,true);}} var env=scene.getEnvironment();env.checkSanity();var bgnd=scene.getBackground();this.setupScene(gl,bgnd);this.numFaces=0;this.numCoords=0;this.numDrawCalls=0;var mat_proj=viewarea.getProjectionMatrix();var mat_view=viewarea.getViewMatrix();if(!this._calledViewpointChangedHandler||!viewarea._last_mat_view.equals(mat_view)){var e_viewpoint=scene.getViewpoint();var e_eventType="viewpointChanged";try {if(e_viewpoint.hasEventListener(e_eventType)||scene.hasEventListener(e_eventType)) {var e_viewtrafo=e_viewpoint.getCurrentTransform();e_viewtrafo=e_viewtrafo.inverse().mult(mat_view);var e_mat=e_viewtrafo.inverse();var e_rotation=new x3dom.fields.Quaternion(0,0,1,0);e_rotation.setValue(e_mat);var e_translation=e_mat.e3();var e_event={target:e_viewpoint._xmlNode,type:e_eventType,matrix:e_viewtrafo,position:e_translation,orientation:e_rotation.toAxisAngle(),cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;},preventDefault:function(){this.cancelBubble=true;}};if(e_viewpoint.hasEventListener(e_eventType)) {e_viewpoint.callEvtHandler(("on"+e_eventType),e_event);} if(scene.hasEventListener(e_eventType)) {scene.callEvtHandler(("on"+e_eventType),e_event);} e_viewpoint.callEvtHandler(("on"+e_eventType),e_event);this._calledViewpointChangedHandler=true;}} catch(e_e) {x3dom.debug.logException(e_e);}} viewarea._last_mat_view=mat_view;viewarea._last_mat_proj=mat_proj;var mat_scene=mat_proj.mult(mat_view);viewarea._last_mat_scene=mat_scene;scene.drawableCollection=null;if(!scene.drawableCollection){var drawableCollectionConfig={viewArea:viewarea,sortTrans:env._vf.sortTrans,viewMatrix:mat_view,projMatrix:mat_proj,sceneMatrix:mat_scene,frustumCulling:true,smallFeatureThreshold:env._smallFeatureThreshold,context:this,gl:gl};scene.drawableCollection=new x3dom.DrawableCollection(drawableCollectionConfig);x3dom.Utils.startMeasure('traverse');scene.collectDrawableObjects(x3dom.fields.SFMatrix4f.identity(),scene.drawableCollection,true,false,0,[]);var traverseTime=x3dom.Utils.stopMeasure('traverse');this.x3dElem.runtime.addMeasurement('TRAVERSE',traverseTime);} x3dom.Utils.startMeasure('sorting');scene.drawableCollection.sort();var sortTime=x3dom.Utils.stopMeasure('sorting');this.x3dElem.runtime.addMeasurement('SORT',sortTime);var slights=viewarea.getLights();var numLights=slights.length;var mat_light;var WCToLCMatrices=[];var lMatrices=[];var shadowCount=0;x3dom.Utils.startMeasure('shadow');for(var p=0;p0.0){var lightMatrix=viewarea.getLightMatrix()[p];var shadowMaps=scene._webgl.fboShadow[shadowCount];var offset=Math.max(0.0,Math.min(1.0,slights[p]._vf.shadowOffset));if(!x3dom.isa(slights[p],x3dom.nodeTypes.PointLight)){var numCascades=Math.max(1,Math.min(slights[p]._vf.shadowCascades,6));mat_light=viewarea.getWCtoLCMatricesCascaded(lightMatrix,slights[p],mat_proj);for(i=0;i0||x3dom.SSAO.isEnabled(scene)){this.renderShadowPass(gl,viewarea,mat_scene,mat_view,scene._webgl.fboScene,0.0,true);var shadowTime=x3dom.Utils.stopMeasure('shadow');this.x3dElem.runtime.addMeasurement('SHADOW',shadowTime);}else{this.x3dElem.runtime.removeMeasurement('SHADOW');} mat_light=viewarea.getWCtoLCMatrix(viewarea.getLightMatrix()[0]);for(rtl_i=0;rtl_i0) this.renderShadows(gl,viewarea,shadowedLights,WCToLCMatrices,lMatrices,mat_view,mat_proj,mat_scene);this.stateManager.disable(gl.BLEND);this.stateManager.disable(gl.DEPTH_TEST);viewarea._numRenderedNodes=n;if(x3dom.SSAO.isEnabled(scene)) x3dom.SSAO.renderSSAO(this.stateManager,gl,scene,this.canvas);if(viewarea._visDbgBuf!==undefined&&viewarea._visDbgBuf){var pm=scene._vf.pickMode.toLowerCase();if(pm.indexOf("idbuf")==0||pm=="color"||pm=="texcoord"){this.stateManager.viewport(0,3*this.canvas.height/4,this.canvas.width/4,this.canvas.height/4);scene._fgnd._webgl.render(gl,scene._webgl.fboPick.tex);} if(shadowCount>0||x3dom.SSAO.isEnabled(scene)){this.stateManager.viewport(this.canvas.width/4,3*this.canvas.height/4,this.canvas.width/4,this.canvas.height/4);scene._fgnd._webgl.render(gl,scene._webgl.fboScene.tex);} var row=3,col=2;for(i=0;i1){sp.lastTex=1;gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,rt._webgl.fbo.tex);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);} sp.curTex=2;gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,rt._webgl.texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);sp.mode=rt._currLoadLevel-1;sp.repeat=rt._repeat.toGL();gl.drawArrays(gl.TRIANGLES,0,6);this.stateManager.bindFramebuffer(gl.FRAMEBUFFER,rt._webgl.fbo.fbo);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);sp.mode=0;sp.curTex=2;gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,refinementFbo.tex);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.drawArrays(gl.TRIANGLES,0,6);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,null);gl.disableVertexAttribArray(sp.position);this.stateManager.bindFramebuffer(gl.FRAMEBUFFER,null);this.stateManager.viewport(0,0,this.canvas.width,this.canvas.height);if(rt._vf.autoRefinement) rt.nextLevel();if(rt._currLoadLevel==rt._vf.maxLevel) rt._currLoadLevel++;if(rt._webgl.fbo.mipMap){gl.bindTexture(gl.TEXTURE_2D,rt._webgl.fbo.tex);gl.generateMipmap(gl.TEXTURE_2D);gl.bindTexture(gl.TEXTURE_2D,null);} if(!rt.requirePingPong()){gl.deleteTexture(rt._webgl.texture);delete rt._webgl.texture;rt._cleanupGLObjects(true);} rt._renderedImage++;};Context.prototype.renderRTPass=function(gl,viewarea,rt){if(x3dom.isa(rt,x3dom.nodeTypes.RefinementTexture)){if(rt.requirePingPong()){this.renderPingPongPass(gl,viewarea,rt);} return;} switch(rt._vf.update.toUpperCase()){case"NONE":return;case"NEXT_FRAME_ONLY":if(!rt._needRenderUpdate){return;} rt._needRenderUpdate=false;break;case"ALWAYS":default:break;} var scene=viewarea._scene;var bgnd=null;var mat_view=rt.getViewMatrix();var mat_proj=rt.getProjectionMatrix();var mat_scene=mat_proj.mult(mat_view);var lightMatrix=viewarea.getLightMatrix()[0];var mat_light=viewarea.getWCtoLCMatrix(lightMatrix);var i,n,m=rt._cf.excludeNodes.nodes.length;var arr=new Array(m);for(i=0;i0||s_gl.popGeometry>0){for(v=0,offset=0,v_n=s_geo._vf.vertexCount.length;v0)){this.drawElements(gl,s_gl.primType[0],s_geo._vf.vertexCount[0],s_gl.indexType,shape._indexOffset);}else if(s_gl.bufferGeometry<0){this.drawArrays(gl,s_gl.primType[0],0,s_geo._vf.vertexCount[0]);}else if(s_geo.hasIndexOffset()){var indOff=shape.tessellationProperties();for(v=0,v_n=indOff.length;vtexLimit){renderSplit[renderSplit.length]=i;texUnits=7;}} renderSplit[renderSplit.length]=shadowedLights.length;var n=renderSplit.length-1;var mat_proj_inv=mat_proj.inverse();var mat_scene_inv=mat_scene.inverse();this.stateManager.enable(gl.BLEND);this.stateManager.blendFunc(gl.DST_COLOR,gl.ZERO);for(var s=0;s=0)?url.substr(0,i+1):"";x3dom.debug.logInfo("setBaseURL: "+this.baseURL);};x3dom.NodeNameSpace.prototype.getURL=function(url){if(url===undefined||!url.length){return"";}else{return((url[0]==='/')||(url.indexOf(":")>=0))?url:(this.baseURL+url);}};x3dom.hasElementAttribute=function(attrName){var ok=this.__hasAttribute(attrName);if(!ok&&attrName){ok=this.__hasAttribute(attrName.toLowerCase());} return ok;};x3dom.getElementAttribute=function(attrName){var attrib=this.__getAttribute(attrName);if(!attrib&&attrib!=""&&attrName){attrib=this.__getAttribute(attrName.toLowerCase());} if(attrib||!this._x3domNode){return attrib;}else{return this._x3domNode._vf[attrName];}};x3dom.setElementAttribute=function(attrName,newVal){this.__setAttribute(attrName,newVal);var x3dNode=this._x3domNode;if(x3dNode){x3dNode.updateField(attrName,newVal);x3dNode._nameSpace.doc.needRender=true;}};x3dom.getFieldValue=function(fieldName){var x3dNode=this._x3domNode;if(x3dNode&&(x3dNode._vf[fieldName]!==undefined)){var fieldValue=x3dNode._vf[fieldName];if(fieldValue instanceof Object&&'copy'in fieldValue){return x3dNode._vf[fieldName].copy();}else{return x3dNode._vf[fieldName];}} return null;};x3dom.setFieldValue=function(fieldName,fieldvalue){var x3dNode=this._x3domNode;if(x3dNode&&(x3dNode._vf[fieldName]!==undefined)){if(fieldvalue instanceof Object&&'copy'in fieldvalue){x3dNode._vf[fieldName]=fieldvalue.copy();}else{x3dNode._vf[fieldName]=fieldvalue;} x3dNode.fieldChanged(fieldName);x3dNode._nameSpace.doc.needRender=true;}};x3dom.requestFieldRef=function(fieldName){var x3dNode=this._x3domNode;if(x3dNode&&x3dNode._vf[fieldName]){return x3dNode._vf[fieldName];} return null;};x3dom.releaseFieldRef=function(fieldName){var x3dNode=this._x3domNode;if(x3dNode&&x3dNode._vf[fieldName]){x3dNode.fieldChanged(fieldName);x3dNode._nameSpace.doc.needRender=true;}};x3dom.NodeNameSpace.prototype.setupTree=function(domNode,parent){var n=null;parent=parent||null;if(x3dom.isX3DElement(domNode)){if(domNode._x3domNode){x3dom.debug.logWarning('Tree is already initialized');return null;} if((domNode.tagName!==undefined)&&(!domNode.__addEventListener)&&(!domNode.__removeEventListener)){domNode.__addEventListener=domNode.addEventListener;domNode.addEventListener=function(type,func,phase){if(!this._x3domNode._listeners[type]){this._x3domNode._listeners[type]=[];} this._x3domNode._listeners[type].push(func);this.__addEventListener(type,func,phase);};domNode.__removeEventListener=domNode.removeEventListener;domNode.removeEventListener=function(type,func,phase){var list=this._x3domNode._listeners[type];if(list){for(var it=0;it=2){var otherNS=this;while(otherNS){if(otherNS.name==nsName[0]) n=otherNS.defMap[nsName[1]];if(n){otherNS=null;}else{otherNS=otherNS.parent;}} if(!n){n=null;x3dom.debug.logWarning('Could not USE: '+domNode.getAttribute('USE'));}}} if(n){domNode._x3domNode=n;} return n;}else{if(domNode.localName.toLowerCase()==='route'){var route=domNode;var fnAtt=route.getAttribute('fromNode')||route.getAttribute('fromnode');var tnAtt=route.getAttribute('toNode')||route.getAttribute('tonode');var fromNode=this.defMap[fnAtt];var toNode=this.defMap[tnAtt];if(!(fromNode&&toNode)){x3dom.debug.logWarning("Broken route - can't find all DEFs for "+fnAtt+" -> "+tnAtt);}else{fnAtt=route.getAttribute('fromField')||route.getAttribute('fromfield');tnAtt=route.getAttribute('toField')||route.getAttribute('tofield');fromNode.setupRoute(fnAtt,toNode,tnAtt);route._nodeNameSpace=this;} return null;} domNode.requestFieldRef=x3dom.requestFieldRef;domNode.releaseFieldRef=x3dom.releaseFieldRef;domNode.getFieldValue=x3dom.getFieldValue;domNode.setFieldValue=x3dom.setFieldValue;var nodeType=x3dom.nodeTypesLC[domNode.localName.toLowerCase()];if(nodeType===undefined){x3dom.debug.logWarning("Unrecognised X3D element <"+domNode.localName+">.");}else{if((x3dom.userAgentFeature.supportsDOMAttrModified===false)&&(domNode instanceof Element)){if(domNode.setAttribute&&!domNode.__setAttribute){domNode.__setAttribute=domNode.setAttribute;domNode.setAttribute=x3dom.setElementAttribute;} if(domNode.getAttribute&&!domNode.__getAttribute){domNode.__getAttribute=domNode.getAttribute;domNode.getAttribute=x3dom.getElementAttribute;} if(domNode.hasAttribute&&!domNode.__hasAttribute){domNode.__hasAttribute=domNode.hasAttribute;domNode.hasAttribute=x3dom.hasElementAttribute;}} var ctx={doc:this.doc,xmlNode:domNode,nameSpace:this};n=new nodeType(ctx);if(domNode.hasAttribute('DEF')){n._DEF=domNode.getAttribute('DEF');this.defMap[n._DEF]=n;}else{if(domNode.hasAttribute('id')){n._DEF=domNode.getAttribute('id');this.defMap[n._DEF]=n;}} if(domNode.highlight===undefined){domNode.highlight=function(enable,colorStr){var color=x3dom.fields.SFColor.parse(colorStr);this._x3domNode.highlight(enable,color);this._x3domNode._nameSpace.doc.needRender=true;};} n._xmlNode=domNode;domNode._x3domNode=n;var that=this;Array.forEach(domNode.childNodes,function(childDomNode){var c=that.setupTree(childDomNode,n);if(c){n.addChild(c,childDomNode.getAttribute("containerField"));}});n.nodeChanged();return n;}}}else if(domNode.localName){if(parent&&domNode.localName.toLowerCase()=="x3dommetagroup"){Array.forEach(domNode.childNodes,function(childDomNode){var c=this.setupTree(childDomNode,parent);if(c){parent.addChild(c,childDomNode.getAttribute("containerField"));}}.bind(this));}else{x3dom.debug.logWarning("Unrecognised X3D element <"+domNode.localName+">.");n=null;}} return n;};x3dom.registerNodeType("X3DNode","Core",defineClass(null,function(ctx){this._xmlNode=null;this._DEF=null;this._nameSpace=(ctx&&ctx.nameSpace)?ctx.nameSpace:null;this._vf={};this._vfFieldTypes={};this._cf={};this._cfFieldTypes={};this._fieldWatchers={};this._routes={};this._listeners={};this._parentNodes=[];this._childNodes=[];this.addField_SFNode('metadata',x3dom.nodeTypes.X3DMetadataObject);},{type:function(){return this.constructor;},typeName:function(){return this.constructor._typeName;},addChild:function(node,containerFieldName){if(node){var field=null;if(containerFieldName){field=this._cf[containerFieldName];} else{for(var fieldName in this._cf){if(this._cf.hasOwnProperty(fieldName)){var testField=this._cf[fieldName];if(x3dom.isa(node,testField.type)){field=testField;break;}}}} if(field&&field.addLink(node)){node._parentNodes.push(this);this._childNodes.push(node);node.parentAdded(this);return true;}} return false;},removeChild:function(node){if(node){for(var fieldName in this._cf){if(this._cf.hasOwnProperty(fieldName)){var field=this._cf[fieldName];if(field.rmLink(node)){for(var i=node._parentNodes.length-1;i>=0;i--){if(node._parentNodes[i]===this){node._parentNodes.splice(i,1);node.parentRemoved(this);}} for(var j=this._childNodes.length-1;j>=0;j--){if(this._childNodes[j]===node){node.onRemove();this._childNodes.splice(j,1);return true;}}}}}} return false;},onRemove:function(){},parentAdded:function(parent){},parentRemoved:function(parent){for(var i=0,n=this._childNodes.length;i=1){return this.transformMatrix(this._parentNodes[0].getCurrentTransform());} else{return x3dom.fields.SFMatrix4f.identity();}},transformMatrix:function(transform){return transform;},getVolume:function(){return null;},invalidateVolume:function(){},invalidateCache:function(){},volumeValid:function(){return false;},collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes){},highlight:function(enable,color) {if(this._vf.hasOwnProperty("diffuseColor")) {if(enable){if(this._actDiffuseColor===undefined){this._actDiffuseColor=new x3dom.fields.SFColor();this._highlightOn=false;} if(!this._highlightOn){this._actDiffuseColor.setValues(this._vf.diffuseColor);this._highlightOn=true;} this._vf.diffuseColor.setValues(color);} else{if(this._actDiffuseColor!==undefined){this._vf.diffuseColor.setValues(this._actDiffuseColor);this._highlightOn=false;delete this._actDiffuseColor;}}} for(var i=0,n=this._childNodes.length;i0){fieldName=fromField.substr(0,fromField.length-post.length);if(this._vf[fieldName]!==undefined){fromField=fieldName;}}}} if(!toNode._vf[toField]){pos=toField.indexOf(pre);if(pos===0){fieldName=toField.substr(pre.length,toField.length-1);if(toNode._vf[fieldName]!==undefined){toField=fieldName;}} else{pos=toField.indexOf(post);if(pos>0){fieldName=toField.substr(0,toField.length-post.length);if(toNode._vf[fieldName]!==undefined){toField=fieldName;}}}} var where=this._DEF+"&"+fromField+"&"+toNode._DEF+"&"+toField;if(!this._routes[where]){if(!this._fieldWatchers[fromField]){this._fieldWatchers[fromField]=[];} this._fieldWatchers[fromField].push(function(msg){toNode.postMessage(toField,msg);});if(!toNode._fieldWatchers[toField]){toNode._fieldWatchers[toField]=[];} toNode._fieldWatchers[toField].push(function(msg){toNode._vf[toField]=msg;toNode.fieldChanged(toField);});this._routes[where]={from:this._fieldWatchers[fromField].length-1,to:toNode._fieldWatchers[toField].length-1};}},removeRoute:function(fromField,toNode,toField){var pos;var fieldName;var pre="set_",post="_changed";if(!this._vf[fromField]){pos=fromField.indexOf(pre);if(pos===0){fieldName=fromField.substr(pre.length,fromField.length-1);if(this._vf[fieldName]!==undefined){fromField=fieldName;}}else{pos=fromField.indexOf(post);if(pos>0){fieldName=fromField.substr(0,fromField.length-post.length);if(this._vf[fieldName]!==undefined){fromField=fieldName;}}}} if(!toNode._vf[toField]){pos=toField.indexOf(pre);if(pos===0){fieldName=toField.substr(pre.length,toField.length-1);if(toNode._vf[fieldName]!==undefined){toField=fieldName;}} else{pos=toField.indexOf(post);if(pos>0){fieldName=toField.substr(0,toField.length-post.length);if(toNode._vf[fieldName]!==undefined){toField=fieldName;}}}} var where=this._DEF+"&"+fromField+"&"+toNode._DEF+"&"+toField;if(this._routes[where]){this._fieldWatchers[fromField].splice(this._routes[where].from,1);toNode._fieldWatchers[toField].splice(this._routes[where].to,1);delete this._routes[where];}},fieldChanged:function(fieldName){},nodeChanged:function(){},callEvtHandler:function(eventType,event){var node=this;if(!node._xmlNode){return event.cancelBubble;} if(!node._xmlNode.getAttribute(eventType)&&!node._xmlNode[eventType]&&!node._listeners[event.type]) {return event.cancelBubble;} try{var attrib=node._xmlNode[eventType];event.target=node._xmlNode;if(typeof(attrib)==="function"){attrib.call(node._xmlNode,event);} else{var funcStr=node._xmlNode.getAttribute(eventType);var func=new Function('event',funcStr);func.call(node._xmlNode,event);} var list=node._listeners[event.type];if(list){for(var it=0;it=0){this.bind(this._vf.bind);}},nodeChanged:function(){this._stack=this._nameSpace.doc._bindableBag.addBindable(this);}}));x3dom.registerNodeType("X3DInfoNode","Core",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DInfoNode.superClass.call(this,ctx);}));x3dom.registerNodeType("WorldInfo","Core",defineClass(x3dom.nodeTypes.X3DInfoNode,function(ctx){x3dom.nodeTypes.WorldInfo.superClass.call(this,ctx);this.addField_MFString(ctx,'info',[]);this.addField_SFString(ctx,'title',"");x3dom.debug.logInfo(this._vf.info);x3dom.debug.logInfo(this._vf.title);}));x3dom.registerNodeType("X3DSensorNode","Core",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DSensorNode.superClass.call(this,ctx);this.addField_SFBool(ctx,'enabled',true);}));x3dom.registerNodeType("Param","Core",defineClass(x3dom.nodeTypes.X3DNode,function(ctx){x3dom.nodeTypes.Param.superClass.call(this,ctx);x3dom.debug.logWarning('DEPRECATED: Param element needs to be child of X3D element ' +'[DOCS]');}));x3dom.registerNodeType("X3DBoundedObject","Grouping",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DBoundedObject.superClass.call(this,ctx);this.addField_SFBool(ctx,'render',true);this.addField_SFVec3f(ctx,'bboxCenter',0,0,0);this.addField_SFVec3f(ctx,'bboxSize',-1,-1,-1);this._graph={boundedNode:this,localMatrix:x3dom.fields.SFMatrix4f.identity(),globalMatrix:null,volume:new x3dom.fields.BoxVolume(),lastVolume:new x3dom.fields.BoxVolume(),worldVolume:new x3dom.fields.BoxVolume(),center:new x3dom.fields.SFVec3f(0,0,0),coverage:-1,needCulling:true};},{fieldChanged:function(fieldName){if(this._vf.hasOwnProperty(fieldName)){this.invalidateVolume();}},nodeChanged:function(){this.invalidateVolume();},parentAdded:function(parent){this.invalidateVolume();},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {for(var i=0,n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} var n=this._childNodes.length;if(x3dom.nodeTypes.ClipPlane.count>0){var localClipPlanes=[];for(var j=0;j=0&&this._vf.whichChoice1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();if(this._vf.whichChoice<0||this._vf.whichChoice>=this._childNodes.length||(planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask))<0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} if((cnode=this._childNodes[this._vf.whichChoice])){cnode.collectDrawableObjects(childTransform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes);}},doIntersect:function(line) {if(this._vf.whichChoice<0||this._vf.whichChoice>=this._childNodes.length){return false;} var child=this._childNodes[this._vf.whichChoice];if(child){return child.doIntersect(line);} return false;}}));x3dom.registerNodeType("X3DTransformNode","Grouping",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.X3DTransformNode.superClass.call(this,ctx);if(ctx) ctx.doc._nodeBag.trans.push(this);else x3dom.debug.logWarning("X3DTransformNode: No runtime context found!");this._trafo=null;this._needCssStyleUpdates=true;},{tick:function(t) {var dom=this._xmlNode;if(dom&&(dom['ontransform']||dom.hasAttribute('ontransform')||this._listeners['transform'])){var transMatrix=this.getCurrentTransform();var event={target:dom,type:'transform',worldX:transMatrix._03,worldY:transMatrix._13,worldZ:transMatrix._23,cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;}};this.callEvtHandler("ontransform",event);} if(this._needCssStyleUpdates&&dom){var trans=x3dom.getStyle(dom,"-webkit-transform")||x3dom.getStyle(dom,"-moz-transform")||x3dom.getStyle(dom,"-ms-transform")||x3dom.getStyle(dom,"transform");if(trans&&(trans!='none')){this._trafo.setValueByStr(trans);this.invalidateVolume();return true;} this._needCssStyleUpdates=false;} return false;},transformMatrix:function(transform){return transform.mult(this._trafo);},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {this._graph.localMatrix=this._trafo;for(var i=0,n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} if(this.needBvhRebuild) {var drawableCollectionConfig={viewArea:drawableCollection.viewarea,sortTrans:drawableCollection.sortTrans,viewMatrix:drawableCollection.viewMatrix,projMatrix:drawableCollection.projMatrix,sceneMatrix:drawableCollection.sceneMatrix,frustumCulling:false,smallFeatureThreshold:0,context:drawableCollection.context};this.drawableCollection=new x3dom.DrawableCollection(drawableCollectionConfig);var i,n=this._childNodes.length;for(i=0;i0) {that._idList=[];var arr=x3dom.fields.MFString.parse(evt.data);var n=Math.min(arr.length,Math.abs(that._vf.maxRenderedIds));for(var i=0;i0){nodeName=nodeName.substring(0,starInd);matchNameBegin=true;} if(nodeName.length<=1) continue;if((matchNameBegin&&this._vf.label[i].indexOf(nodeName)==0)||this._vf.label[i]==nodeName){this._visibleList[i]=false;break;}}} else{this._visibleList[i]=false;}} this.invalidateVolume();} else if(fieldName=="render"){this.invalidateVolume();}},getNumRenderedObjects:function(len,isMoving) {var n=len;if(this._vf.maxRenderedIds>0) {var num=Math.max(this._vf.maxRenderedIds,16);var scale=1;if(isMoving) scale=Math.min(this._vf.scaleRenderedIdsOnMove,1);num=Math.max(Math.round(scale*num),0);n=Math.min(n,num);} return n;},collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes) {if(singlePath&&(this._parentNodes.length>1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<=0){return;} var viewarea=this._nameSpace.doc._viewarea;var isMoving=viewarea.isMovingOrAnimating();var ts=new Date().getTime();var maxLiveTime=10000;var i,n,numChild=this._childNodes.length;if(!this._vf.enableCulling) {n=this.getNumRenderedObjects(numChild,isMoving);var cnt=0;for(i=0;i0&&ts-this._createTime[i]>maxLiveTime&&shape._cleanupGLObjects) {shape._cleanupGLObjects(true);this._createTime[i]=0;}}} return;} if(this._websocket) this._websocket.updateCamera();if(this._vf.label.length) {n=this.getNumRenderedObjects(this._idList.length,isMoving);for(i=0;i0&&ts-this._createTime[i]>maxLiveTime&&this._childNodes[i]._cleanupGLObjects) {this._childNodes[i]._cleanupGLObjects(true);this._createTime[i]=0;}}}}}));x3dom.registerNodeType("Scene","Grouping",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.Scene.superClass.call(this,ctx);this.addField_SFString(ctx,'pickMode',"idBuf");this.addField_SFBool(ctx,'doPickPass',true);this.addField_SFString(ctx,'shadowObjectIdMapping',"");this._lastMin=new x3dom.fields.SFVec3f(0,0,0);this._lastMax=new x3dom.fields.SFVec3f(1,1,1);this._shadowIdMap=null;this.loadMapping();this._multiPartMap=null;},{fieldChanged:function(fieldName) {if(fieldName=="shadowObjectIdMapping") {this.loadMapping();}},updateVolume:function() {var vol=this.getVolume();if(vol.isValid()) {this._lastMin=x3dom.fields.SFVec3f.copy(vol.min);this._lastMax=x3dom.fields.SFVec3f.copy(vol.max);}},loadMapping:function() {this._shadowIdMap=null;if(this._vf.shadowObjectIdMapping.length==0){return;} var that=this;var xhr=new XMLHttpRequest();xhr.open("GET",this._nameSpace.getURL(this._vf.shadowObjectIdMapping),true);x3dom.RequestManager.addRequest(xhr);xhr.onload=function() {that._shadowIdMap=eval("("+xhr.response+")");if(!that._shadowIdMap||!that._shadowIdMap.mapping){x3dom.debug.logWarning("Invalid ID map: "+that._vf.shadowObjectIdMapping);} else{x3dom.debug.assert(that._shadowIdMap.maxID<=that._shadowIdMap.mapping.length,"Too few ID map entries in "+that._vf.shadowObjectIdMapping+", "+"length of mapping array is only "+that._shadowIdMap.mapping.length+" instead of "+that._shadowIdMap.ids.length+"!");}};}}));x3dom.BindableStack=function(doc,type,defaultType,getter){this._doc=doc;this._type=type;this._defaultType=defaultType;this._defaultRoot=null;this._getter=getter;this._bindBag=[];this._bindStack=[];};x3dom.BindableStack.prototype.top=function(){return((this._bindStack.length>0)?this._bindStack[this._bindStack.length-1]:null);};x3dom.BindableStack.prototype.push=function(bindable){var top=this.top();if(top===bindable){return;} if(top){top.deactivate();} this._bindStack.push(bindable);bindable.activate(top);};x3dom.BindableStack.prototype.replaceTop=function(bindable){var top=this.top();if(top===bindable){return;} if(top){top.deactivate();this._bindStack[this._bindStack.length-1]=bindable;bindable.activate(top);}};x3dom.BindableStack.prototype.pop=function(bindable){var top;if(bindable){top=this.top();if(bindable!==top){return null;}} top=this._bindStack.pop();if(top){top.deactivate();} return top;};x3dom.BindableStack.prototype.switchTo=function(target){var last=this.getActive();var n=this._bindBag.length;var toBind=0;var i=0,lastIndex=-1;if(n<=1){return;} switch(target){case'first':toBind=this._bindBag[0];break;case'last':toBind=this._bindBag[n-1];break;default:for(i=0;i=0){i=lastIndex;while(!toBind){if(target=='next'){i=(i<(n-1))?(i+1):0;}else{i=(i>0)?(i-1):(n-1);} if(i==lastIndex){break;} if(this._bindBag[i]._vf.description.length>=0){toBind=this._bindBag[i];}}} break;} if(toBind){this.replaceTop(toBind);}else{x3dom.debug.logWarning('Cannot switch bindable; no other bindable with description found.');}};x3dom.BindableStack.prototype.getActive=function(){if(this._bindStack.length===0){if(this._bindBag.length===0){if(this._defaultRoot){x3dom.debug.logInfo('create new '+this._defaultType._typeName+' for '+this._type._typeName+'-stack');var obj=new this._defaultType({doc:this._doc,nameSpace:this._defaultRoot._nameSpace,autoGen:true});this._defaultRoot.addChild(obj);obj.nodeChanged();}else{x3dom.debug.logError('stack without defaultRoot');}}else{x3dom.debug.logInfo('activate first '+this._type._typeName+' for '+this._type._typeName+'-stack');} this._bindStack.push(this._bindBag[0]);this._bindBag[0].activate();} return this._bindStack[this._bindStack.length-1];};x3dom.BindableBag=function(doc){this._stacks=[];this.addType("X3DViewpointNode","Viewpoint","getViewpoint",doc);this.addType("X3DNavigationInfoNode","NavigationInfo","getNavigationInfo",doc);this.addType("X3DBackgroundNode","Background","getBackground",doc);this.addType("X3DFogNode","Fog","getFog",doc);this.addType("X3DEnvironmentNode","Environment","getEnvironment",doc);};x3dom.BindableBag.prototype.addType=function(typeName,defaultTypeName,getter,doc){var type=x3dom.nodeTypes[typeName];var defaultType=x3dom.nodeTypes[defaultTypeName];if(type&&defaultType){var stack=new x3dom.BindableStack(doc,type,defaultType,getter);this._stacks.push(stack);}else{x3dom.debug.logWarning('Invalid Bindable type/defaultType: '+ typeName+'/'+defaultType);}};x3dom.BindableBag.prototype.setRefNode=function(node){Array.forEach(this._stacks,function(stack){stack._defaultRoot=node;node[stack._getter]=function(){return stack.getActive();};});};x3dom.BindableBag.prototype.addBindable=function(node){for(var i=0,n=this._stacks.length;i=0;return(this._vf.lit&&hasTris);}}));x3dom.registerNodeType("Mesh","Rendering",defineClass(x3dom.nodeTypes.X3DGeometryNode,function(ctx){x3dom.nodeTypes.Mesh.superClass.call(this,ctx);this.addField_SFString(ctx,'primType',"triangle");this.addField_MFInt32(ctx,'index',[]);this.addField_MFNode('vertexAttributes',x3dom.nodeTypes.X3DVertexAttributeNode);},{nodeChanged:function() {var time0=new Date().getTime();var i,n=this._cf.vertexAttributes.nodes.length;for(i=0;i=0;j--){this._mesh._indices[0].push(cnt++,cnt);if(j==0)cnt++;}}},fieldChanged:function(fieldName){if(fieldName=="coord"){var pnts=this._cf.coord.node.getPoints();this._mesh._positions[0]=pnts.toGL();this.invalidateVolume();Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;node.invalidateVolume();});} else if(fieldName=="color"){var cols=this._cf.color.node._vf.color;this._mesh._colors[0]=cols.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.colors=true;});}}}));x3dom.registerNodeType("IndexedLineSet","Rendering",defineClass(x3dom.nodeTypes.X3DGeometryNode,function(ctx){x3dom.nodeTypes.IndexedLineSet.superClass.call(this,ctx);this.addField_SFBool(ctx,'colorPerVertex',true);this.addField_MFNode('attrib',x3dom.nodeTypes.X3DVertexAttributeNode);this.addField_SFNode('coord',x3dom.nodeTypes.X3DCoordinateNode);this.addField_SFNode('color',x3dom.nodeTypes.X3DColorNode);this.addField_MFInt32(ctx,'coordIndex',[]);this.addField_MFInt32(ctx,'colorIndex',[]);this._mesh._primType='LINES';x3dom.Utils.needLineWidth=true;},{_buildGeometry:function() {var time0=new Date().getTime();var indexes=this._vf.coordIndex;var colorInd=this._vf.colorIndex;var hasColor=false,hasColorInd=false;var colPerVert=this._vf.colorPerVertex;if(colorInd.length==indexes.length) {hasColorInd=true;} var positions,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode.getPoints();var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode) {hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._indices[0]=[];this._mesh._positions[0]=[];this._mesh._colors[0]=[];var i,t,cnt,lineCnt;var p0,p1,c0,c1;if((hasColor&&hasColorInd)||positions.length>x3dom.Utils.maxIndexableCoords) {t=0;cnt=0;lineCnt=0;for(i=0;ipositions.length-1) {continue;} if(indexes[i]===-1){t=0;continue;} if(hasColorInd){x3dom.debug.assert(colorInd[i]!=-1);} switch(t) {case 0:p0=+indexes[i];if(hasColorInd&&colPerVert){c0=+colorInd[i];} else{c0=p0;} t=1;break;case 1:p1=+indexes[i];if(hasColorInd&&colPerVert){c1=+colorInd[i];} else if(hasColorInd&&!colPerVert){c1=+colorInd[lineCnt];} else{c1=p1;} this._mesh._indices[0].push(cnt++,cnt++);this._mesh._positions[0].push(positions[p0].x);this._mesh._positions[0].push(positions[p0].y);this._mesh._positions[0].push(positions[p0].z);this._mesh._positions[0].push(positions[p1].x);this._mesh._positions[0].push(positions[p1].y);this._mesh._positions[0].push(positions[p1].z);if(hasColor){if(!colPerVert){c0=c1;} this._mesh._colors[0].push(colors[c0].r);this._mesh._colors[0].push(colors[c0].g);this._mesh._colors[0].push(colors[c0].b);this._mesh._colors[0].push(colors[c1].r);this._mesh._colors[0].push(colors[c1].g);this._mesh._colors[0].push(colors[c1].b);} t=2;lineCnt++;break;case 2:p0=p1;c0=c1;p1=+indexes[i];if(hasColorInd&&colPerVert){c1=+colorInd[i];} else if(hasColorInd&&!colPerVert){c1=+colorInd[lineCnt];} else{c1=p1;} this._mesh._indices[0].push(cnt++,cnt++);this._mesh._positions[0].push(positions[p0].x);this._mesh._positions[0].push(positions[p0].y);this._mesh._positions[0].push(positions[p0].z);this._mesh._positions[0].push(positions[p1].x);this._mesh._positions[0].push(positions[p1].y);this._mesh._positions[0].push(positions[p1].z);if(hasColor){if(!colPerVert){c0=c1;} this._mesh._colors[0].push(colors[c0].r);this._mesh._colors[0].push(colors[c0].g);this._mesh._colors[0].push(colors[c0].b);this._mesh._colors[0].push(colors[c1].r);this._mesh._colors[0].push(colors[c1].g);this._mesh._colors[0].push(colors[c1].b);} lineCnt++;break;default:}} if(positions.length>x3dom.Utils.maxIndexableCoords) this._mesh.splitMesh(2);} else {var n=indexes.length;t=0;for(i=0;i0){positions.push(positions.length-1);} posMax=positions.length;if(!normPerVert||!colPerVert||posMax>x3dom.Utils.maxIndexableCoords) {t=0;cnt=0;faceCnt=0;this._mesh._multiIndIndices=[];this._mesh._posSize=positions.length;for(i=0;i0)&&(i%3===0)){t=0;faceCnt++;} switch(t) {case 0:p0=+indexes[i];if(normPerVert){n0=p0;}else if(!normPerVert){n0=faceCnt;} t0=p0;if(colPerVert){c0=p0;}else if(!colPerVert){c0=faceCnt;} t=1;break;case 1:p1=+indexes[i];if(normPerVert){n1=p1;}else if(!normPerVert){n1=faceCnt;} t1=p1;if(colPerVert){c1=p1;}else if(!colPerVert){c1=faceCnt;} t=2;break;case 2:p2=+indexes[i];if(normPerVert){n2=p2;}else if(!normPerVert){n2=faceCnt;} t2=p2;if(colPerVert){c2=p2;}else if(!colPerVert){c2=faceCnt;} t=3;this._mesh._indices[0].push(cnt++,cnt++,cnt++);this._mesh._positions[0].push(positions[p0].x);this._mesh._positions[0].push(positions[p0].y);this._mesh._positions[0].push(positions[p0].z);this._mesh._positions[0].push(positions[p1].x);this._mesh._positions[0].push(positions[p1].y);this._mesh._positions[0].push(positions[p1].z);this._mesh._positions[0].push(positions[p2].x);this._mesh._positions[0].push(positions[p2].y);this._mesh._positions[0].push(positions[p2].z);if(hasNormal){this._mesh._normals[0].push(normals[n0].x);this._mesh._normals[0].push(normals[n0].y);this._mesh._normals[0].push(normals[n0].z);this._mesh._normals[0].push(normals[n1].x);this._mesh._normals[0].push(normals[n1].y);this._mesh._normals[0].push(normals[n1].z);this._mesh._normals[0].push(normals[n2].x);this._mesh._normals[0].push(normals[n2].y);this._mesh._normals[0].push(normals[n2].z);} else{this._mesh._multiIndIndices.push(p0,p1,p2);} if(hasColor){this._mesh._colors[0].push(colors[c0].r);this._mesh._colors[0].push(colors[c0].g);this._mesh._colors[0].push(colors[c0].b);if(numColComponents===4){this._mesh._colors[0].push(colors[c0].a);} this._mesh._colors[0].push(colors[c1].r);this._mesh._colors[0].push(colors[c1].g);this._mesh._colors[0].push(colors[c1].b);if(numColComponents===4){this._mesh._colors[0].push(colors[c1].a);} this._mesh._colors[0].push(colors[c2].r);this._mesh._colors[0].push(colors[c2].g);this._mesh._colors[0].push(colors[c2].b);if(numColComponents===4){this._mesh._colors[0].push(colors[c2].a);}} if(hasTexCoord){this._mesh._texCoords[0].push(texCoords[t0].x);this._mesh._texCoords[0].push(texCoords[t0].y);if(numTexComponents===3){this._mesh._texCoords[0].push(texCoords[t0].z);} this._mesh._texCoords[0].push(texCoords[t1].x);this._mesh._texCoords[0].push(texCoords[t1].y);if(numTexComponents===3){this._mesh._texCoords[0].push(texCoords[t1].z);} this._mesh._texCoords[0].push(texCoords[t2].x);this._mesh._texCoords[0].push(texCoords[t2].y);if(numTexComponents===3){this._mesh._texCoords[0].push(texCoords[t2].z);}} break;default:}} if(!hasNormal){this._mesh.calcNormals(normPerVert?Math.PI:0);} if(!hasTexCoord){this._mesh.calcTexCoords(texMode);} this._mesh.splitMesh();} else {faceCnt=0;for(i=0;i0)&&(i%3===0)){faceCnt++;} this._mesh._indices[0].push(indexes[i]);if(!normPerVert&&hasNormal){this._mesh._normals[0].push(normals[faceCnt].x);this._mesh._normals[0].push(normals[faceCnt].y);this._mesh._normals[0].push(normals[faceCnt].z);} if(!colPerVert&&hasColor){this._mesh._colors[0].push(colors[faceCnt].r);this._mesh._colors[0].push(colors[faceCnt].g);this._mesh._colors[0].push(colors[faceCnt].b);if(numColComponents===4){this._mesh._colors[0].push(colors[faceCnt].a);}}} this._mesh._positions[0]=positions.toGL();if(hasNormal){this._mesh._normals[0]=normals.toGL();} else{this._mesh.calcNormals(normPerVert?Math.PI:0,ccw);} if(hasTexCoord){this._mesh._texCoords[0]=texCoords.toGL();this._mesh._numTexComponents=numTexComponents;} else{this._mesh.calcTexCoords(texMode);} if(hasColor&&colPerVert){this._mesh._colors[0]=colors.toGL();this._mesh._numColComponents=numColComponents;}} this.invalidateVolume();this._mesh._numFaces=0;this._mesh._numCoords=0;for(i=0;ix3dom.Utils.maxIndexableCoords) {x3dom.debug.logWarning("IndexedTriangleSet: fieldChanged with "+"too many coordinates not yet implemented!");return;} if(fieldName=="coord") {this._mesh._positions[0]=pnts.toGL();this.invalidateVolume();Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;node.invalidateVolume();});} else if(fieldName=="color") {pnts=this._cf.color.node._vf.color;if(this._vf.colorPerVertex){this._mesh._colors[0]=pnts.toGL();}else if(!this._vf.colorPerVertex){var faceCnt=0;var numColComponents=3;if(x3dom.isa(this._cf.color.node,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;} this._mesh._colors[0]=[];var indexes=this._vf.index;for(var i=0;i0)&&(i%3===0)){faceCnt++;} this._mesh._colors[0].push(pnts[faceCnt].r);this._mesh._colors[0].push(pnts[faceCnt].g);this._mesh._colors[0].push(pnts[faceCnt].b);if(numColComponents===4){this._mesh._colors[0].push(pnts[faceCnt].a);}}} Array.forEach(this._parentNodes,function(node){node._dirty.colors=true;});} else if(fieldName=="normal") {pnts=this._cf.normal.node._vf.vector;if(this._vf.normalPerVertex){this._mesh._normals[0]=pnts.toGL();}else if(!this._vf.normalPerVertex){var indexes=this._vf.index;this._mesh._normals[0]=[];var faceCnt=0;for(var i=0;i0)&&(i%3===0)){faceCnt++;} this._mesh._normals[0].push(pnts[faceCnt].x);this._mesh._normals[0].push(pnts[faceCnt].y);this._mesh._normals[0].push(pnts[faceCnt].z);}} Array.forEach(this._parentNodes,function(node){node._dirty.normals=true;});} else if(fieldName=="texCoord") {var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} pnts=texCoordNode._vf.point;this._mesh._texCoords[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.texcoords=true;});}}}));x3dom.registerNodeType("IndexedTriangleStripSet","Rendering",defineClass(x3dom.nodeTypes.X3DComposedGeometryNode,function(ctx){x3dom.nodeTypes.IndexedTriangleStripSet.superClass.call(this,ctx);this.addField_MFInt32(ctx,'index',[]);this._hasIndexOffset=false;this._indexOffset=null;},{hasIndexOffset:function(){return this._hasIndexOffset;},nodeChanged:function() {this.handleAttribs();var hasNormal=false,hasTexCoord=false,hasColor=false;var colPerVert=this._vf.colorPerVertex;var normPerVert=this._vf.normalPerVertex;var indexes=this._vf.index;if(indexes.length&&indexes[indexes.length-1]!=-1) {indexes.push(-1);} var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode._vf.point;var normalNode=this._cf.normal.node;if(normalNode){hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode){if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.TextureCoordinate3D)){numTexComponents=3;}} else if(texCoordNode._vf.mode){texMode=texCoordNode._vf.mode;}} else{hasTexCoord=false;} this._mesh._numTexComponents=numTexComponents;var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode){hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._numColComponents=numColComponents;this._mesh._indices[0]=[];this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._colors[0]=[];this.invalidateVolume();this._mesh._numFaces=0;this._mesh._numCoords=0;var faceCnt=0,cnt=0;if(hasNormal&&positions.length<=x3dom.Utils.maxIndexableCoords) {this._hasIndexOffset=true;this._indexOffset=[];this._mesh._primType='TRIANGLESTRIP';var i,indexOffset=[0];for(i=0;ix3dom.Utils.maxIndexableCoords)) {if(fieldName=="coord"){this._mesh._positions[0]=[];this._mesh._indices[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];var hasNormal=false,hasTexCoord=false,hasColor=false;var colPerVert=this._vf.colorPerVertex;var normPerVert=this._vf.normalPerVertex;var indexes=this._vf.index;var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode._vf.point;var normalNode=this._cf.normal.node;if(normalNode){hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode){if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.TextureCoordinate3D)){numTexComponents=3;}} else if(texCoordNode._vf.mode){texMode=texCoordNode._vf.mode;}} else{hasTexCoord=false;} this._mesh._numTexComponents=numTexComponents;var numColComponents=3;var colorNode=this._cf.color.node;if(colorNode){hasColor=true;colors=colorNode._vf.color;if(x3dom.isa(colorNode,x3dom.nodeTypes.ColorRGBA)){numColComponents=4;}} else{hasColor=false;} this._mesh._numColComponents=numColComponents;this._mesh._indices[0]=[];this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._colors[0]=[];var faceCnt=0,cnt=0;var p1,p2,p3,n1,n2,n3,t1,t2,t3,c1,c2,c3;var swapOrder=false;if(hasNormal||hasTexCoord||hasColor){for(var i=1;i0){positions.pop();} this._mesh._indices[0]=new Array(positions.length);this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._colors[0]=[];var posMax=positions.length/3;var faceCnt,i=0;for(faceCnt=0;faceCnt0||this._cf.material.node._vf.backTransparency&&this._cf.material.node._vf.backTransparency>0)){this._vf.sortType='transparent';} else if(this._cf.texture.node&&this._cf.texture.node._vf.url.length){if(this._cf.texture.node._vf.url[0].toLowerCase().indexOf('.'+'png')>=0){this._vf.sortType='transparent';} else{this._vf.sortType='opaque';}} else if(x3dom.isa(this._cf.material.node,x3dom.nodeTypes.PhysicalMaterial)) {var material=this._cf.material.node;if(material._vf.alphaMode=="OPAQUE") {this._vf.sortType='opaque';} else if(material._vf.alphaMode=="BLEND"||material._vf.alphaMode=="MASK") {this._vf.sortType='transparent';} var baseColorTexture=material._cf.baseColorTexture.node;if(this._vf.sortType=='opaque'&&baseColorTexture&&baseColorTexture._vf.url.length&&baseColorTexture._vf.url[0].toLowerCase().indexOf('.png')>=0) {this._vf.sortType='transparent';}} else{this._vf.sortType='opaque';}}},texTransformMatrix:function(){if(this._cf.textureTransform.node===null){return x3dom.fields.SFMatrix4f.identity();} else{return this._cf.textureTransform.node.texTransformMatrix();}},parentAdded:function(parent){if(this!=x3dom.nodeTypes.Appearance._defaultNode){parent.setAppDirty();}}}));x3dom.nodeTypes.Appearance.defaultNode=function(){if(!x3dom.nodeTypes.Appearance._defaultNode){x3dom.nodeTypes.Appearance._defaultNode=new x3dom.nodeTypes.Appearance();x3dom.nodeTypes.Appearance._defaultNode.nodeChanged();} return x3dom.nodeTypes.Appearance._defaultNode;};x3dom.registerNodeType("X3DAppearanceChildNode","Shape",defineClass(x3dom.nodeTypes.X3DNode,function(ctx){x3dom.nodeTypes.X3DAppearanceChildNode.superClass.call(this,ctx);}));x3dom.registerNodeType("BlendMode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.BlendMode.superClass.call(this,ctx);this.addField_SFString(ctx,'srcFactor',"src_alpha");this.addField_SFString(ctx,'destFactor',"one_minus_src_alpha");this.addField_SFColor(ctx,'color',1,1,1);this.addField_SFFloat(ctx,'colorTransparency',0);this.addField_SFString(ctx,'alphaFunc',"none");this.addField_SFFloat(ctx,'alphaFuncValue',0);this.addField_SFString(ctx,'equation',"none");}));x3dom.registerNodeType("DepthMode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.DepthMode.superClass.call(this,ctx);this.addField_SFBool(ctx,'enableDepthTest',true);this.addField_SFString(ctx,'depthFunc',"none");this.addField_SFBool(ctx,'readOnly',false);this.addField_SFFloat(ctx,'zNearRange',-1);this.addField_SFFloat(ctx,'zFarRange',-1);}));x3dom.registerNodeType("ColorMaskMode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.ColorMaskMode.superClass.call(this,ctx);this.addField_SFBool(ctx,'maskR',true);this.addField_SFBool(ctx,'maskG',true);this.addField_SFBool(ctx,'maskB',true);this.addField_SFBool(ctx,'maskA',true);}));x3dom.registerNodeType("LineProperties","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.LineProperties.superClass.call(this,ctx);this.addField_SFBool(ctx,'applied',true);this.addField_SFInt32(ctx,'linetype',1);this.addField_SFFloat(ctx,'linewidthScaleFactor',0);}));x3dom.registerNodeType("X3DMaterialNode","Shape",defineClass(x3dom.nodeTypes.X3DAppearanceChildNode,function(ctx){x3dom.nodeTypes.X3DMaterialNode.superClass.call(this,ctx);}));x3dom.registerNodeType("Material","Shape",defineClass(x3dom.nodeTypes.X3DMaterialNode,function(ctx){x3dom.nodeTypes.Material.superClass.call(this,ctx);this.addField_SFFloat(ctx,'ambientIntensity',0.2);this.addField_SFColor(ctx,'diffuseColor',0.8,0.8,0.8);this.addField_SFColor(ctx,'emissiveColor',0,0,0);this.addField_SFFloat(ctx,'shininess',0.2);this.addField_SFColor(ctx,'specularColor',0,0,0);this.addField_SFFloat(ctx,'transparency',0);},{fieldChanged:function(fieldName){if(fieldName=="ambientIntensity"||fieldName=="diffuseColor"||fieldName=="emissiveColor"||fieldName=="shininess"||fieldName=="specularColor"||fieldName=="transparency") {Array.forEach(this._parentNodes,function(app){Array.forEach(app._parentNodes,function(shape){shape._dirty.material=true;});app.checkSortType();});}}}));x3dom.nodeTypes.Material.defaultNode=function(){if(!x3dom.nodeTypes.Material._defaultNode){x3dom.nodeTypes.Material._defaultNode=new x3dom.nodeTypes.Material();x3dom.nodeTypes.Material._defaultNode.nodeChanged();} return x3dom.nodeTypes.Material._defaultNode;};x3dom.registerNodeType("TwoSidedMaterial","Shape",defineClass(x3dom.nodeTypes.Material,function(ctx){x3dom.nodeTypes.TwoSidedMaterial.superClass.call(this,ctx);this.addField_SFFloat(ctx,'backAmbientIntensity',0.2);this.addField_SFColor(ctx,'backDiffuseColor',0.8,0.8,0.8);this.addField_SFColor(ctx,'backEmissiveColor',0,0,0);this.addField_SFFloat(ctx,'backShininess',0.2);this.addField_SFColor(ctx,'backSpecularColor',0,0,0);this.addField_SFFloat(ctx,'backTransparency',0);this.addField_SFBool(ctx,'separateBackColor',false);},{fieldChanged:function(fieldName){if(fieldName=="ambientIntensity"||fieldName=="diffuseColor"||fieldName=="emissiveColor"||fieldName=="shininess"||fieldName=="specularColor"||fieldName=="transparency"||fieldName=="backAmbientIntensity"||fieldName=="backDiffuseColor"||fieldName=="backEmissiveColor"||fieldName=="backShininess"||fieldName=="backSpecularColor"||fieldName=="backTransparency"||fieldName=="separateBackColor") {Array.forEach(this._parentNodes,function(app){Array.forEach(app._parentNodes,function(shape){shape._dirty.material=true;});app.checkSortType();});}}}));x3dom.registerNodeType("PhysicalMaterial","Shape",defineClass(x3dom.nodeTypes.X3DMaterialNode,function(ctx){x3dom.nodeTypes.X3DMaterialNode.superClass.call(this,ctx);this.addField_SFString(ctx,'model',"roughnessMetallic");this.addField_SFColorRGBA(ctx,'baseColorFactor',1,1,1,1);this.addField_SFFloat(ctx,'metallicFactor',0);this.addField_SFFloat(ctx,'roughnessFactor',0.2);this.addField_SFColorRGBA(ctx,'diffuseFactor',1,1,1,1);this.addField_SFColor(ctx,'specularFactor',1,1,1);this.addField_SFFloat(ctx,'glossinessFactor',1);this.addField_SFColor(ctx,'emissiveFactor',0,0,0);this.addField_SFString(ctx,'normalSpace','TANGENT');this.addField_SFString(ctx,'alphaMode','OPAQUE');this.addField_SFFloat(ctx,'alphaCutoff',0.5);this.addField_SFVec3f(ctx,'normalBias',-1,-1,1);this.addField_SFFloat(ctx,'normalScale',1);this.addField_SFBool(ctx,'unlit',false);this.addField_SFNode('baseColorTexture',x3dom.nodeTypes.X3DTextureNode);this.addField_SFNode('emissiveTexture',x3dom.nodeTypes.X3DTextureNode);this.addField_SFNode('roughnessMetallicTexture',x3dom.nodeTypes.X3DTextureNode);this.addField_SFNode('specularGlossinessTexture',x3dom.nodeTypes.X3DTextureNode);this.addField_SFNode('occlusionRoughnessMetallicTexture',x3dom.nodeTypes.X3DTextureNode);this.addField_SFNode('normalTexture',x3dom.nodeTypes.X3DTextureNode);this.addField_SFNode('occlusionTexture',x3dom.nodeTypes.X3DTextureNode);},{fieldChanged:function(fieldName) {if(fieldName=="baseColorFactor"||fieldName=="metallicFactor"||fieldName=="roughnessFactor"||fieldName=="emissiveFactor") {Array.forEach(this._parentNodes,function(app){Array.forEach(app._parentNodes,function(shape){shape._dirty.material=true;});app.checkSortType();});} if(fieldName=="alphaMode") {Array.forEach(this._parentNodes,function(app){Array.forEach(app._parentNodes,function(shape){shape._dirty.shader=true;});app.checkSortType();});}},hasTextures:function() {return(this._cf.baseColorTexture.node||this._cf.normalTexture.node||this._cf.occlusionTexture.node||this._cf.emissiveTexture.node||this._cf.roughnessMetallicTexture.node);},getTextures:function() {var textures=[];if(this._cf.baseColorTexture.node) {this._cf.baseColorTexture.node._type="diffuseMap";textures.push(this._cf.baseColorTexture.node);} if(this._cf.normalTexture.node) {this._cf.normalTexture.node._type="normalMap";textures.push(this._cf.normalTexture.node);} if(this._cf.occlusionTexture.node) {this._cf.occlusionTexture.node._type="occlusionMap";textures.push(this._cf.occlusionTexture.node);} if(this._cf.emissiveTexture.node) {this._cf.emissiveTexture.node._type="emissiveMap";textures.push(this._cf.emissiveTexture.node);} if(this._cf.roughnessMetallicTexture.node) {this._cf.roughnessMetallicTexture.node._type="roughnessMetallicMap";textures.push(this._cf.roughnessMetallicTexture.node);} if(this._cf.specularGlossinessTexture.node) {this._cf.specularGlossinessTexture.node._type="specularGlossinessMap";textures.push(this._cf.specularGlossinessTexture.node);} if(this._cf.occlusionRoughnessMetallicTexture.node) {this._cf.occlusionRoughnessMetallicTexture.node._type="occlusionRoughnessMetallicMap";textures.push(this._cf.occlusionRoughnessMetallicTexture.node);} return textures;}}));x3dom.registerNodeType("X3DShapeNode","Shape",defineClass(x3dom.nodeTypes.X3DBoundedObject,function(ctx){x3dom.nodeTypes.X3DShapeNode.superClass.call(this,ctx);this.addField_SFBool(ctx,'isPickable',true);this.addField_SFInt32(ctx,'idOffset',0);this.addField_SFNode('appearance',x3dom.nodeTypes.X3DAppearanceNode);this.addField_SFNode('geometry',x3dom.nodeTypes.X3DGeometryNode);this._objectID=0;this._shaderProperties=null;this._clipPlanes=[];this._cleanupGLObjects=null;this._dirty={positions:true,normals:true,texcoords:true,colors:true,tangents:true,binormals:true,specialAttribs:true,indexes:true,texture:true,material:true,text:true,shader:true,ids:true};this._indexOffset=0;this._coordStrideOffset=[0,0];this._normalStrideOffset=[0,0];this._texCoordStrideOffset=[0,0];this._texCoord2StrideOffset=[0,0];this._colorStrideOffset=[0,0];this._idStrideOffset=[0,0];this._tangentStrideOffset=[0,0];this._binormalStrideOffset=[0,0];this._tessellationProperties=[];},{collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes) {var graphState=this.graphState();if(singlePath&&(this._parentNodes.length>1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();if(!this._cf.geometry.node||drawableCollection.cull(transform,graphState,singlePath,planeMask)<=0){return false;} if(singlePath&&!this._graph.globalMatrix) this._graph.globalMatrix=transform;if(this._clipPlanes.length!=clipPlanes.length) {this._dirty.shader=true;} this._clipPlanes=clipPlanes;drawableCollection.addShape(this,transform,graphState);return true;},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {var geo=this._cf.geometry.node;var childVol=geo?geo.getVolume():null;if(childVol&&childVol.isValid()) vol.extendBounds(childVol.min,childVol.max);} return vol;},getCenter:function(){var geo=this._cf.geometry.node;return(geo?geo.getCenter():new x3dom.fields.SFVec3f(0,0,0));},getDiameter:function(){var geo=this._cf.geometry.node;return(geo?geo.getDiameter():0);},doIntersect:function(line){return this._cf.geometry.node.doIntersect(line);},forceUpdateCoverage:function() {var geo=this._cf.geometry.node;return(geo?geo.forceUpdateCoverage():false);},tessellationProperties:function() {var geo=this._cf.geometry.node;if(geo&&geo._indexOffset) return geo._indexOffset;else return this._tessellationProperties;},isLit:function(){return this._cf.geometry.node._vf.lit;},isSolid:function(){var twoSidedMat=(this._cf.appearance.node&&this._cf.appearance.node._cf.material.node&&x3dom.isa(this._cf.appearance.node._cf.material.node,x3dom.nodeTypes.TwoSidedMaterial));return this._cf.geometry.node._vf.solid&&!twoSidedMat;},isCCW:function(){return this._cf.geometry.node._vf.ccw;},parentRemoved:function(parent){for(var i=0,n=this._childNodes.length;i0) this.invalidateVolume();if(this._cleanupGLObjects){this._cleanupGLObjects();}},unsetDirty:function(){this._dirty.positions=false;this._dirty.normals=false;this._dirty.texcoords=false;this._dirty.colors=false;this._dirty.tangents=false;this._dirty.binormals=false;this._dirty.specialAttribs=false;this._dirty.indexes=false;this._dirty.texture=false;this._dirty.material=false;this._dirty.text=false;this._dirty.shader=false;},unsetGeoDirty:function(){this._dirty.positions=false;this._dirty.normals=false;this._dirty.texcoords=false;this._dirty.colors=false;this._dirty.tangents=false;this._dirty.binormals=false;this._dirty.specialAttribs=false;this._dirty.indexes=false;},setAllDirty:function(){this._dirty.positions=true;this._dirty.normals=true;this._dirty.texcoords=true;this._dirty.colors=true;this._dirty.tangents=true;this._dirty.binormals=true;this._dirty.specialAttribs=true;this._dirty.indexes=true;this._dirty.texture=true;this._dirty.material=true;this._dirty.text=true;this._dirty.shader=true;this.invalidateVolume();},setAppDirty:function(){this._dirty.texture=true;this._dirty.material=true;this._dirty.shader=true;},setGeoDirty:function(){this._dirty.positions=true;this._dirty.normals=true;this._dirty.texcoords=true;this._dirty.colors=true;this._dirty.tangents=true;this._dirty.binormals=true;this._dirty.specialAttribs=true;this._dirty.indexes=true;this.invalidateVolume();},getShaderProperties:function(viewarea) {if(this._shaderProperties==null||this._dirty.shader==true||x3dom.Utils.checkDirtyEnvironment(viewarea,this._shaderProperties)||x3dom.Utils.checkDirtyPhysicalEnvironmentLight(viewarea,this._shaderProperties)||(this._webgl!==undefined&&this._webgl.dirtyLighting!=x3dom.Utils.checkDirtyLighting(viewarea))) {this._shaderProperties=x3dom.Utils.generateProperties(viewarea,this);this._dirty.shader=false;if(this._webgl!==undefined) {this._webgl.dirtyLighting=x3dom.Utils.checkDirtyLighting(viewarea);}} return this._shaderProperties;},getTextures:function(){var textures=[];var appearance=this._cf.appearance.node;if(appearance){var tex=appearance._cf.texture.node;if(tex){if(x3dom.isa(tex,x3dom.nodeTypes.MultiTexture)){textures=textures.concat(tex.getTextures());} else{textures.push(tex);}} var shader=appearance._cf.shaders.nodes[0];if(shader){if(x3dom.isa(shader,x3dom.nodeTypes.CommonSurfaceShader)){textures=textures.concat(shader.getTextures());}} var material=appearance._cf.material.node;if(material){if(x3dom.isa(material,x3dom.nodeTypes.PhysicalMaterial)){textures=textures.concat(material.getTextures());}}} var geometry=this._cf.geometry.node;if(geometry){if(x3dom.isa(geometry,x3dom.nodeTypes.ImageGeometry)){textures=textures.concat(geometry.getTextures());} else if(x3dom.isa(geometry,x3dom.nodeTypes.Text)){textures=textures.concat(geometry);}} return textures;}}));x3dom.registerNodeType("Shape","Shape",defineClass(x3dom.nodeTypes.X3DShapeNode,function(ctx){x3dom.nodeTypes.Shape.superClass.call(this,ctx);},{nodeChanged:function(){if(!this._cf.appearance.node){} if(!this._cf.geometry.node){if(this._DEF) x3dom.debug.logError("No geometry given in Shape/"+this._DEF);} else if(!this._objectID){this._objectID=++x3dom.nodeTypes.Shape.objectID;x3dom.nodeTypes.Shape.idMap.nodeID[this._objectID]=this;} this.setAllDirty();}}));x3dom.nodeTypes.Shape.shaderPartID=0;x3dom.nodeTypes.Shape.objectID=0;x3dom.nodeTypes.Shape.idMap={nodeID:{},remove:function(obj){for(var prop in this.nodeID){if(this.nodeID.hasOwnProperty(prop)){var val=this.nodeID[prop];if(val._objectID&&obj._objectID&&val._objectID===obj._objectID) {delete this.nodeID[prop];x3dom.debug.logInfo("Unreg "+val._objectID);}}}}};x3dom.registerNodeType("ExternalShape","Shape",defineClass(x3dom.nodeTypes.X3DShapeNode,function(ctx){x3dom.nodeTypes.ExternalShape.superClass.call(this,ctx);this.addField_MFString(ctx,'url',[]);this._currentURLIdx=0;this._cf.geometry.node=new x3dom.nodeTypes.X3DSpatialGeometryNode(ctx);this.loaded=false;},{update:function(shape,shaderProgram,gl,viewarea,context){var that=this;if(this._vf['url'].length==0||this._currentURLIdx>=this._vf['url'].length) {return;} var url=this._nameSpace.getURL(this._vf['url'][this._currentURLIdx]);var encoding=(url.indexOf("glb")!=-1)?"binary":"ascii";var baseURL=this._nameSpace.baseURL;var index=url.lastIndexOf("/");if(index!=-1) {baseURL+=url.substr(0,index+1);} var xhr=new XMLHttpRequest();xhr.open("GET",this._nameSpace.getURL(this._vf['url'][this._currentURLIdx]),true);xhr.responseType=(encoding=="binary")?"arraybuffer":"json";xhr.send(null);xhr.onerror=function(){x3dom.debug.logError("Unable to load SRC data from URL \""+that._vf['url'][that._currentURLIdx]+"\"");};xhr.onload=function(){if((xhr.status==200||xhr.status==0)){var glTF=new x3dom.glTF.glTFLoader(false,encoding,baseURL);glTF.load(xhr.response,function() {if(glTF.header.sceneLength>0) {that.glTF=glTF;var url=that._vf['url'][that._currentURLIdx];if(url.includes('#')) {var split=url.split('#');var meshName=split[split.length-1];glTF.getMesh(shape,shaderProgram,gl,meshName);} else {glTF.getScene(shape,shaderProgram,gl);} for(var key in glTF._mesh){if(!glTF._mesh.hasOwnProperty(key))continue;that._cf.geometry.node._mesh[key]=glTF._mesh[key];}} else {if((that._currentURLIdx+1)1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();if(singlePath&&!this._graph.globalMatrix) this._graph.globalMatrix=transform;if(this._clipPlanes.length!=clipPlanes.length) {this._dirty.shader=true;} this._clipPlanes=clipPlanes;drawableCollection.addShape(this,transform,graphState);return true;},getShaderProperties:function(viewarea) {var properties=x3dom.Utils.generateProperties(viewarea,this);properties.CSHADER=-1;properties.LIGHTS=viewarea.getLights().length+(viewarea._scene.getNavigationInfo()._vf.headlight);properties.EMPTY_SHADER=1;return properties;},nodeChanged:function() {if(!this._objectID){this._objectID=++x3dom.nodeTypes.Shape.objectID;x3dom.nodeTypes.Shape.idMap.nodeID[this._objectID]=this;}}}));x3dom.registerNodeType("X3DLightNode","Lighting",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DLightNode.superClass.call(this,ctx);if(ctx) ctx.doc._nodeBag.lights.push(this);else x3dom.debug.logWarning("X3DLightNode: No runtime context found!");this._lightID=0;this._dirty=true;this.addField_SFFloat(ctx,'ambientIntensity',0);this.addField_SFColor(ctx,'color',1,1,1);this.addField_SFFloat(ctx,'intensity',1);this.addField_SFBool(ctx,'global',false);this.addField_SFBool(ctx,'on',true);this.addField_SFFloat(ctx,'shadowIntensity',0);this.addField_SFInt32(ctx,'shadowMapSize',1024);this.addField_SFInt32(ctx,'shadowFilterSize',0);this.addField_SFFloat(ctx,'shadowOffset',0);this.addField_SFFloat(ctx,'zNear',-1);this.addField_SFFloat(ctx,'zFar',-1);},{getViewMatrix:function(vec){return x3dom.fields.SFMatrix4f.identity;},nodeChanged:function(){if(!this._lightID){this._lightID=++x3dom.nodeTypes.X3DLightNode.lightID;}},fieldChanged:function(fieldName) {if(this._vf.hasOwnProperty(fieldName)){this._dirty=true;}},parentRemoved:function(parent) {if(this._parentNodes.length===1&&this._parentNodes[0]==parent){var doc=this.findX3DDoc();for(var i=0,n=doc._nodeBag.lights.length;i=this._vf.duration){return 1;} return this.stepResponseCore(t/this._vf.duration);},stepResponseCore:function(T) {return 0.5-0.5*Math.cos(T*Math.PI);}}));x3dom.registerNodeType("X3DChaserNode","Followers",defineClass(x3dom.nodeTypes.X3DFollowerNode,function(ctx){x3dom.nodeTypes.X3DChaserNode.superClass.call(this,ctx);this.addField_SFTime(ctx,'duration',1);this._initDone=false;this._stepTime=0;this._currTime=0;this._bufferEndTime=0;this._numSupports=60;}));x3dom.registerNodeType("X3DDamperNode","Followers",defineClass(x3dom.nodeTypes.X3DFollowerNode,function(ctx){x3dom.nodeTypes.X3DDamperNode.superClass.call(this,ctx);this.addField_SFTime(ctx,'tau',0.3);this.addField_SFFloat(ctx,'tolerance',-1);this.addField_SFInt32(ctx,'order',3);this._eps=this._vf.tolerance<0?this._eps:this._vf.tolerance;this._lastTick=0;}));x3dom.registerNodeType("ColorChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.ColorChaser.superClass.call(this,ctx);this.addField_SFColor(ctx,'initialDestination',0.8,0.8,0.8);this.addField_SFColor(ctx,'initialValue',0.8,0.8,0.8);this.addField_SFColor(ctx,'value',0,0,0);this.addField_SFColor(ctx,'destination',0,0,0);this._buffer=new x3dom.fields.MFColor();this._previousValue=new x3dom.fields.SFColor(0,0,0);this._value=new x3dom.fields.SFColor(0,0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C].subtract(this._buffer[C+1]);DeltaOut=DeltaIn.multiply(this.stepResponse((C+Frac)*this._stepTime));Output=Output.add(DeltaOut);} if(!Output.equals(this._value,this._eps)){this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=this._buffer[C-NumToShift];} for(C=0;C=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},distance:function(a,b) {var diff=a.subtract(b);return Math.sqrt(diff.r*diff.r+diff.g*diff.g+diff.b*diff.b);},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.add(this._value1.subtract(this._value0).multiply(alpha)):new x3dom.fields.SFColor(this._value0.r,this._value0.g,this._value0.b);this._value2=this._vf.order>1&&this._vf.tau?this._value1.add(this._value2.subtract(this._value1).multiply(alpha)):new x3dom.fields.SFColor(this._value1.r,this._value1.g,this._value1.b);this._value3=this._vf.order>2&&this._vf.tau?this._value2.add(this._value3.subtract(this._value2).multiply(alpha)):new x3dom.fields.SFColor(this._value2.r,this._value2.g,this._value2.b);this._value4=this._vf.order>3&&this._vf.tau?this._value3.add(this._value4.subtract(this._value3).multiply(alpha)):new x3dom.fields.SFColor(this._value3.r,this._value3.g,this._value3.b);this._value5=this._vf.order>4&&this._vf.tau?this._value4.add(this._value5.subtract(this._value4).multiply(alpha)):new x3dom.fields.SFColor(this._value4.r,this._value4.g,this._value4.b);var dist=this.distance(this._value1,this._value0);if(this._vf.order>1) {var dist2=this.distance(this._value2,this._value1);if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=this.distance(this._value3,this._value2);if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=this.distance(this._value4,this._value3);if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=this.distance(this._value5,this._value4);if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("OrientationChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.OrientationChaser.superClass.call(this,ctx);this.addField_SFRotation(ctx,'initialDestination',0,1,0,0);this.addField_SFRotation(ctx,'initialValue',0,1,0,0);this.addField_SFRotation(ctx,'value',0,1,0,0);this.addField_SFRotation(ctx,'destination',0,1,0,0);this._numSupports=30;this._buffer=new x3dom.fields.MFRotation();this._previousValue=new x3dom.fields.Quaternion(0,1,0,0);this._value=new x3dom.fields.Quaternion(0,1,0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C+1].inverse().multiply(this._buffer[C]);Output=Output.slerp(Output.multiply(DeltaIn),this.stepResponse((C+Frac)*this._stepTime));} if(!Output.equals(this._value,this._eps)){Output=Output.normalize(Output);this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=x3dom.fields.Quaternion.copy(this._buffer[C-NumToShift]);} for(C=0;C=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.slerp(this._value1,alpha):new x3dom.fields.Quaternion(this._value0.x,this._value0.y,this._value0.z,this._value0.w);this._value2=this._vf.order>1&&this._vf.tau?this._value1.slerp(this._value2,alpha):new x3dom.fields.Quaternion(this._value1.x,this._value1.y,this._value1.z,this._value1.w);this._value3=this._vf.order>2&&this._vf.tau?this._value2.slerp(this._value3,alpha):new x3dom.fields.Quaternion(this._value2.x,this._value2.y,this._value2.z,this._value2.w);this._value4=this._vf.order>3&&this._vf.tau?this._value3.slerp(this._value4,alpha):new x3dom.fields.Quaternion(this._value3.x,this._value3.y,this._value3.z,this._value3.w);this._value5=this._vf.order>4&&this._vf.tau?this._value4.slerp(this._value5,alpha):new x3dom.fields.Quaternion(this._value4.x,this._value4.y,this._value4.z,this._value4.w);var dist=Math.abs(this._value1.inverse().multiply(this._value0).angle());if(this._vf.order>1) {var dist2=Math.abs(this._value2.inverse().multiply(this._value1).angle());if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=Math.abs(this._value3.inverse().multiply(this._value2).angle());if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=Math.abs(this._value4.inverse().multiply(this._value3).angle());if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=Math.abs(this._value5.inverse().multiply(this._value4).angle());if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("PositionChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.PositionChaser.superClass.call(this,ctx);this.addField_SFVec3f(ctx,'initialDestination',0,0,0);this.addField_SFVec3f(ctx,'initialValue',0,0,0);this.addField_SFVec3f(ctx,'value',0,0,0);this.addField_SFVec3f(ctx,'destination',0,0,0);this._buffer=new x3dom.fields.MFVec3f();this._previousValue=new x3dom.fields.SFVec3f(0,0,0);this._value=new x3dom.fields.SFVec3f(0,0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C].subtract(this._buffer[C+1]);DeltaOut=DeltaIn.multiply(this.stepResponse((C+Frac)*this._stepTime));Output=Output.add(DeltaOut);} if(!Output.equals(this._value,this._eps)){this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=x3dom.fields.SFVec3f.copy(this._buffer[C-NumToShift]);} for(C=0;C=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue.setValues(this._vf.value);for(var C=1;C=0;C--) {DeltaIn=this._buffer[C].subtract(this._buffer[C+1]);DeltaOut=DeltaIn.multiply(this.stepResponse((C+Frac)*this._stepTime));Output=Output.add(DeltaOut);} if(!Output.equals(this._value,this._eps)){this._value.setValues(Output);this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=x3dom.fields.SFVec2f.copy(this._buffer[C-NumToShift]);} for(C=0;C=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.add(this._value1.subtract(this._value0).multiply(alpha)):new x3dom.fields.SFVec3f(this._value0.x,this._value0.y,this._value0.z);this._value2=this._vf.order>1&&this._vf.tau?this._value1.add(this._value2.subtract(this._value1).multiply(alpha)):new x3dom.fields.SFVec3f(this._value1.x,this._value1.y,this._value1.z);this._value3=this._vf.order>2&&this._vf.tau?this._value2.add(this._value3.subtract(this._value2).multiply(alpha)):new x3dom.fields.SFVec3f(this._value2.x,this._value2.y,this._value2.z);this._value4=this._vf.order>3&&this._vf.tau?this._value3.add(this._value4.subtract(this._value3).multiply(alpha)):new x3dom.fields.SFVec3f(this._value3.x,this._value3.y,this._value3.z);this._value5=this._vf.order>4&&this._vf.tau?this._value4.add(this._value5.subtract(this._value4).multiply(alpha)):new x3dom.fields.SFVec3f(this._value4.x,this._value4.y,this._value4.z);var dist=this._value1.subtract(this._value0).length();if(this._vf.order>1) {var dist2=this._value2.subtract(this._value1).length();if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=this._value3.subtract(this._value2).length();if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=this._value4.subtract(this._value3).length();if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=this._value5.subtract(this._value4).length();if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("PositionDamper2D","Followers",defineClass(x3dom.nodeTypes.X3DDamperNode,function(ctx){x3dom.nodeTypes.PositionDamper2D.superClass.call(this,ctx);this.addField_SFVec2f(ctx,'initialDestination',0,0);this.addField_SFVec2f(ctx,'initialValue',0,0);this.addField_SFVec2f(ctx,'value',0,0);this.addField_SFVec2f(ctx,'destination',0,0);this._value0=new x3dom.fields.SFVec2f(0,0);this._value1=new x3dom.fields.SFVec2f(0,0);this._value2=new x3dom.fields.SFVec2f(0,0);this._value3=new x3dom.fields.SFVec2f(0,0);this._value4=new x3dom.fields.SFVec2f(0,0);this._value5=new x3dom.fields.SFVec2f(0,0);this.initialize();},{fieldChanged:function(fieldName) {if(fieldName==="tolerance") {this._eps=this._vf.tolerance<0?0.001:this._vf.tolerance;} else if(fieldName.indexOf("destination")>=0) {if(!this._value0.equals(this._vf.destination,this._eps)){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1.setValues(this._vf.value);this._value2.setValues(this._vf.value);this._value3.setValues(this._vf.value);this._value4.setValues(this._vf.value);this._value5.setValues(this._vf.value);this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0.setValues(this._vf.initialDestination);this._value1.setValues(this._vf.initialValue);this._value2.setValues(this._vf.initialValue);this._value3.setValues(this._vf.initialValue);this._value4.setValues(this._vf.initialValue);this._value5.setValues(this._vf.initialValue);this._lastTick=0;var active=!this._value0.equals(this._value1,this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0.add(this._value1.subtract(this._value0).multiply(alpha)):new x3dom.fields.SFVec2f(this._value0.x,this._value0.y,this._value0.z);this._value2=this._vf.order>1&&this._vf.tau?this._value1.add(this._value2.subtract(this._value1).multiply(alpha)):new x3dom.fields.SFVec2f(this._value1.x,this._value1.y,this._value1.z);this._value3=this._vf.order>2&&this._vf.tau?this._value2.add(this._value3.subtract(this._value2).multiply(alpha)):new x3dom.fields.SFVec2f(this._value2.x,this._value2.y,this._value2.z);this._value4=this._vf.order>3&&this._vf.tau?this._value3.add(this._value4.subtract(this._value3).multiply(alpha)):new x3dom.fields.SFVec2f(this._value3.x,this._value3.y,this._value3.z);this._value5=this._vf.order>4&&this._vf.tau?this._value4.add(this._value5.subtract(this._value4).multiply(alpha)):new x3dom.fields.SFVec2f(this._value4.x,this._value4.y,this._value4.z);var dist=this._value1.subtract(this._value0).length();if(this._vf.order>1) {var dist2=this._value2.subtract(this._value1).length();if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=this._value3.subtract(this._value2).length();if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=this._value4.subtract(this._value3).length();if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=this._value5.subtract(this._value4).length();if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1.setValues(this._value0);this._value2.setValues(this._value0);this._value3.setValues(this._value0);this._value4.setValues(this._value0);this._value5.setValues(this._value0);this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("ScalarChaser","Followers",defineClass(x3dom.nodeTypes.X3DChaserNode,function(ctx){x3dom.nodeTypes.ScalarChaser.superClass.call(this,ctx);this.addField_SFFloat(ctx,'initialDestination',0);this.addField_SFFloat(ctx,'initialValue',0);this.addField_SFFloat(ctx,'value',0);this.addField_SFFloat(ctx,'destination',0);this._buffer=[];this._previousValue=0;this._value=0;this.initialize();},{fieldChanged:function(fieldName) {if(fieldName.indexOf("destination")>=0) {this.initialize();this.updateBuffer(this._currTime);if(!this._vf.isActive){this.postMessage('isActive',true);}} else if(fieldName.indexOf("value")>=0) {this.initialize();this._previousValue=this._vf.value;for(var C=1;Cthis._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}}},tick:function(now) {this.initialize();this._currTime=now;if(!this._bufferEndTime) {this._bufferEndTime=now;this._value=this._vf.initialValue;this.postMessage('value',this._value);return true;} var Frac=this.updateBuffer(now);var Output=this._previousValue;var DeltaIn=this._buffer[this._buffer.length-1]-this._previousValue;var DeltaOut=DeltaIn*(this.stepResponse((this._buffer.length-1+Frac)*this._stepTime));Output=Output+DeltaOut;for(var C=this._buffer.length-2;C>=0;C--) {DeltaIn=this._buffer[C]-this._buffer[C+1];DeltaOut=DeltaIn*(this.stepResponse((C+Frac)*this._stepTime));Output=Output+DeltaOut;} if(Math.abs(Output-this._value)>this._eps){this._value=Output;this.postMessage('value',this._value);} else{this.postMessage('isActive',false);} return this._vf.isActive;},updateBuffer:function(now) {var Frac=(now-this._bufferEndTime)/this._stepTime;var C;var NumToShift;var Alpha;if(Frac>=1) {NumToShift=Math.floor(Frac);Frac-=NumToShift;if(NumToShift=NumToShift;C--){this._buffer[C]=this._buffer[C-NumToShift];} for(C=0;C=0) {if(Math.abs(this._value0-this._vf.destination)>this._eps){this._value0=this._vf.destination;if(!this._vf.isActive){this.postMessage('isActive',true);}}} else if(fieldName.indexOf("value")>=0) {this._value1=this._vf.value;this._value2=this._vf.value;this._value3=this._vf.value;this._value4=this._vf.value;this._value5=this._vf.value;this._lastTick=0;this.postMessage('value',this._value5);if(!this._vf.isActive){this._lastTick=0;this.postMessage('isActive',true);}}},initialize:function() {this._value0=this._vf.initialDestination;this._value1=this._vf.initialValue;this._value2=this._vf.initialValue;this._value3=this._vf.initialValue;this._value4=this._vf.initialValue;this._value5=this._vf.initialValue;this._lastTick=0;var active=(Math.abs(this._value0-this._value1)>this._eps);if(this._vf.isActive!==active){this.postMessage('isActive',active);}},tick:function(now) {if(!this._lastTick) {this._lastTick=now;return false;} var delta=now-this._lastTick;var alpha=Math.exp(-delta/this._vf.tau);this._value1=this._vf.order>0&&this._vf.tau?this._value0+alpha*(this._value1-this._value0):this._value0;this._value2=this._vf.order>1&&this._vf.tau?this._value1+alpha*(this._value2-this._value1):this._value1;this._value3=this._vf.order>2&&this._vf.tau?this._value2+alpha*(this._value3-this._value2):this._value2;this._value4=this._vf.order>3&&this._vf.tau?this._value3+alpha*(this._value4-this._value3):this._value3;this._value5=this._vf.order>4&&this._vf.tau?this._value4+alpha*(this._value5-this._value4):this._value4;var dist=Math.abs(this._value1-this._value0);if(this._vf.order>1) {var dist2=Math.abs(this._value2-this._value1);if(dist2>dist){dist=dist2;}} if(this._vf.order>2) {var dist3=Math.abs(this._value3-this._value2);if(dist3>dist){dist=dist3;}} if(this._vf.order>3) {var dist4=Math.abs(this._value4-this._value3);if(dist4>dist){dist=dist4;}} if(this._vf.order>4) {var dist5=Math.abs(this._value5-this._value4);if(dist5>dist){dist=dist5;}} if(dist<=this._eps) {this._value1=this._value0;this._value2=this._value0;this._value3=this._value0;this._value4=this._value0;this._value5=this._value0;this.postMessage('value',this._value0);this.postMessage('isActive',false);this._lastTick=0;return false;} this.postMessage('value',this._value5);this._lastTick=now;return true;}}));x3dom.registerNodeType("CoordinateDamper","Followers",defineClass(x3dom.nodeTypes.X3DDamperNode,function(ctx){x3dom.nodeTypes.CoordinateDamper.superClass.call(this,ctx);this.addField_MFVec3f(ctx,'initialDestination',[]);this.addField_MFVec3f(ctx,'initialValue',[]);this.addField_MFVec3f(ctx,'value',[]);this.addField_MFVec3f(ctx,'destination',[]);x3dom.debug.logWarning("CoordinateDamper NYI");}));x3dom.registerNodeType("TexCoordDamper2D","Followers",defineClass(x3dom.nodeTypes.X3DDamperNode,function(ctx){x3dom.nodeTypes.TexCoordDamper2D.superClass.call(this,ctx);this.addField_MFVec2f(ctx,'initialDestination',[]);this.addField_MFVec2f(ctx,'initialValue',[]);this.addField_MFVec2f(ctx,'value',[]);this.addField_MFVec2f(ctx,'destination',[]);x3dom.debug.logWarning("TexCoordDamper2D NYI");}));x3dom.registerNodeType("X3DInterpolatorNode","Interpolation",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DInterpolatorNode.superClass.call(this,ctx);this.addField_MFFloat(ctx,'key',[]);this.addField_SFFloat(ctx,'set_fraction',0);this.addField_SFString(ctx,'buffer',"");this.addField_SFString(ctx,'interpolation',"LINEAR");this.addField_SFFloat(ctx,'duration',0);this.addField_MFNode('views',x3dom.nodeTypes.BufferView);this.addField_MFNode('accessors',x3dom.nodeTypes.BufferAccessor);this._lastValue=undefined;this.normalizeFromType={"5120":function(c){return Math.max(c/127.0,-1.0)},"5121":function(c){return c/255.0;},"5122":function(c){return Math.max(c/32767.0,-1.0)},"5123":function(c){return c/65535.0;},"5125":function(c){return c/4294967295;},"5126":function(c){return c;},};},{nodeChanged:function() {if(this._vf.buffer) {x3dom.BinaryContainerLoader.setupBufferInterpolator(this);}},linearInterp:function(time,interp) {if(this._vf.key.length==0) {return;} if(time<=this._vf.key[0]) {return this._vf.keyValue[0];} else if(time>=this._vf.key[this._vf.key.length-1]) {return this._vf.keyValue[this._vf.key.length-1];} for(var i=0,n=this._vf.key.length-1;i=this._vf.key[this._vf.key.length-1]) {return this._vf.keyValue[this._vf.keyValue.length-2];} for(i=0,n=this._vf.key.length-1;i0?this._vf.key.length:1;var len=arr.length/key;for(var i=0;i=2)||(this._vf.keyVelocity.length==0));if(!sane) x3dom.debug.logWarning("SplinePositionInterpolator Node: 'key' , 'keyValue' and/or 'keyVelocity' fields have inappropriate sizes");};this.calcDtot=function() {this.dtot=0.0;for(var i=0;i2) {for(i=0;i0.0){if(this._vf.set_fraction<=this._vf.key[0]) value=x3dom.fields.SFVec3f.copy(this._vf.keyValue[0]);else if(this._vf.set_fraction>=this._vf.key[this._vf.key.length-1]) value=x3dom.fields.SFVec3f.copy(this._vf.keyValue[this._vf.key.length-1]);} for(var i=0;i0){this._updateCycleStopTime();} this._backupStartTime=this._vf.startTime;this._backupStopTime=this._vf.stopTime;this._backupCycleInterval=this._vf.cycleInterval;},{tick:function(time) {if(!this._vf.enabled){this._lastTime=time;return false;} var isActive=(this._vf.cycleInterval>0&&time>=this._vf.startTime&&(time=this._vf.pauseTime&&this._vf.pauseTime>this._vf.resumeTime);if(isPaused&&!this._vf.isPaused){this.postMessage('isPaused',true);this.postMessage('pauseTime',time);}else if(!isPaused&&this._vf.isPaused){this.postMessage('isPaused',false);this.postMessage('resumeTime',time);} if(!isPaused){var cycleFrac=this._getCycleAt(time);var cycle=Math.floor(cycleFrac);var cycleTime=this._vf.startTime+cycle*this._vf.cycleInterval;var adjustTime=0;if(this._vf.stopTime>this._vf.startTime&&this._lastTime=this._vf.stopTime) adjustTime=this._vf.stopTime;else if(this._lastTime=cycleTime) adjustTime=cycleTime;if(adjustTime>0){time=adjustTime;cycleFrac=this._getCycleAt(time);cycle=Math.floor(cycleFrac);} var fraction=cycleFrac-cycle;if(fraction=0) anchor=url.slice(aPos+1);var param=this._vf.parameter.length?this._vf.parameter[0]:"";var tPos=param.search("target=");var target="";if(tPos>=0) target=param.slice(tPos+7);x3dom.debug.logInfo("Anchor url="+url+", target="+target+", #viewpoint="+anchor);if(target.length!=0||target!="_self"){window.open(this._nameSpace.getURL(url),target);} else{window.location=this._nameSpace.getURL(url);}}}));x3dom.registerNodeType("Inline","Networking",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.Inline.superClass.call(this,ctx);this.addField_MFString(ctx,'url',[]);this.addField_SFBool(ctx,'load',true);this.addField_MFString(ctx,'nameSpaceName',[]);this.addField_SFString(ctx,'contentType',"");this.addField_SFBool(ctx,'mapDEFToID',false);this.initDone=false;this.count=0;this.numRetries=x3dom.nodeTypes.Inline.MaximumRetries;this.ContentType={X3D:"model/x3d+xml",GLTF:"model/gltf+json",GLB:"model/gltf-binary",X3DJ:"model/x3d+json"};},{fieldChanged:function(fieldName) {if(fieldName=="url"||fieldName=="load"){for(var i=0;i=1) {node.removeChild(node.firstChild);}}} this.loadInline();} else if(fieldName=="render"){this.invalidateVolume();}},nodeChanged:function() {if(!this.initDone){this.initDone=true;this.loadInline();}},fireEvents:function(eventType) {if(this._xmlNode&&(this._xmlNode['on'+eventType]||this._xmlNode.hasAttribute('on'+eventType)||this._listeners[eventType])) {var event={target:this._xmlNode,type:eventType,error:(eventType=="error")?"XMLHttpRequest Error":"",cancelBubble:false,stopPropagation:function(){this.cancelBubble=true;}};try{var attrib=this._xmlNode["on"+eventType];if(typeof(attrib)==="function"){attrib.call(this._xmlNode,event);} else{var funcStr=this._xmlNode.getAttribute("on"+eventType);var func=new Function('event',funcStr);func.call(this._xmlNode,event);} var list=this._listeners[eventType];if(list){for(var i=0;i0&&that._childNodes[0]&&that._childNodes[0]._nameSpace) that._nameSpace.removeSpace(that._childNodes[0]._nameSpace);while(that._childNodes.length!==0) global['_remover']=that.removeChild(that._childNodes[0]);delete global['_remover'];if(newScene) {that.addChild(newScene);that.invalidateVolume();var theScene=that._nameSpace.doc._scene;if(theScene){theScene.invalidateVolume();window.setTimeout(function(){that.invalidateVolume();theScene.updateVolume();that._nameSpace.doc.needRender=true;that._nameSpace.doc.decrementDownloads();that._nameSpace.doc.needRender=true;x3dom.debug.logInfo('Inline: added '+that._vf.url[0]+' to scene.');},1000);} that.fireEvents("load");} newScene=null;nameSpace=null;inlScene=null;xml=null;},loadInline:function() {var that=this;var contentType=this.getContentType();var isBinary=false;var xhr=new window.XMLHttpRequest();xhr.onreadystatechange=function() {if(xhr.readyState==4) {if(xhr.status===x3dom.nodeTypes.Inline.AwaitTranscoding) {if(that.count=0)) {nameSpace.setBaseURL(url);} else {nameSpace.setBaseURL(this._nameSpace.baseURL+url);} this._nameSpace.addSpace(nameSpace);return nameSpace;}}));x3dom.nodeTypes.Inline.AwaitTranscoding=202;x3dom.nodeTypes.Inline.MaximumRetries=15;function setNamespace(prefix,childDomNode,mapDEFToID) {if(childDomNode instanceof Element&&childDomNode.__setAttribute!==undefined){if(childDomNode.hasAttribute('id')){childDomNode.__setAttribute('id',prefix.toString().replace(' ','')+'__'+childDomNode.getAttribute('id'));}else if(childDomNode.hasAttribute('DEF')&&mapDEFToID){childDomNode.__setAttribute('id',prefix.toString().replace(' ','')+'__'+childDomNode.getAttribute('DEF'));if(!childDomNode.id) childDomNode.id=childDomNode.__getAttribute('id');}} if(childDomNode.hasChildNodes()){Array.forEach(childDomNode.childNodes,function(children){setNamespace(prefix,children,mapDEFToID);});}} x3dom.registerNodeType("MultiPart","Networking",defineClass(x3dom.nodeTypes.Inline,function(ctx){x3dom.nodeTypes.MultiPart.superClass.call(this,ctx);this.addField_MFString(ctx,'urlIDMap',[]);this.addField_SFBool(ctx,'isPickable',true);this.addField_SFString(ctx,'sortType','auto');this.addField_SFBool(ctx,'solid',false);this.addField_SFInt32(ctx,'sortKey',0);this.addField_SFString(ctx,'initialVisibility','auto');this._idMap=null;this._inlineNamespace=null;this._highlightedParts=[];this._minId=0;this._maxId=0;this._lastId=-1;this._lastClickedId=-1;this._lastButton=0;this._identifierToPartId=[];this._identifierToAppId=[];this._visiblePartsPerShape=[];this._partVolume=[];this._partVisibility=[];this._originalColor=[];this._materials=[];},{fieldChanged:function(fieldName) {if(fieldName=="url"){if(this._vf.nameSpaceName.length!=0){var node=this._xmlNode;if(node&&node.hasChildNodes()) {while(node.childNodes.length>=1) {node.removeChild(node.firstChild);}}} this.loadInline();} else if(fieldName=="render"){this.invalidateVolume();}},nodeChanged:function() {if(!this.initDone){this.initDone=true;this.loadIDMap();}},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {for(var i=0;i0) {selection.push(+id);} else if(mode==1&&intersect==63) {selection.push(+id);}} var colorMap=this._inlineNamespace.defMap["MultiMaterial_ColorMap"];var emissiveMap=this._inlineNamespace.defMap["MultiMaterial_EmissiveMap"];var specularMap=this._inlineNamespace.defMap["MultiMaterial_SpecularMap"];var visibilityMap=this._inlineNamespace.defMap["MultiMaterial_VisibilityMap"];if(selection.length==0){return null;}else{return new x3dom.Parts(this,selection,colorMap,emissiveMap,specularMap,visibilityMap);}},appendAPI:function() {var multiPart=this;this._xmlNode.getIdList=function() {var i,ids=[];for(i=0;i=0)) {that._inlineNamespace.setBaseURL(url);} else {that._inlineNamespace.setBaseURL(that._nameSpace.baseURL+url);} that.replaceMaterials(inlScene);newScene=that._inlineNamespace.setupTree(inlScene);that._nameSpace.addSpace(that._inlineNamespace);if(that._vf.nameSpaceName.length!=0) {Array.forEach(inlScene.childNodes,function(childDomNode) {if(childDomNode instanceof Element) {setNamespace(that._vf.nameSpaceName,childDomNode,that._vf.mapDEFToID);that._xmlNode.appendChild(childDomNode);}});}} else{if(xml&&xml.localName){x3dom.debug.logError('No Scene in '+xml.localName);}else{x3dom.debug.logError('No Scene in resource');}} var global=x3dom.getGlobal();if(that._childNodes.length>0&&that._childNodes[0]&&that._childNodes[0]._nameSpace){that._nameSpace.removeSpace(that._childNodes[0]._nameSpace);} while(that._childNodes.length!==0){global['_remover']=that.removeChild(that._childNodes[0]);} delete global['_remover'];if(newScene) {that.addChild(newScene);that.invalidateVolume();that._nameSpace.doc.decrementDownloads();that._nameSpace.doc.needRender=true;x3dom.debug.logInfo('Inline: added '+that._vf.url[0]+' to scene.');var theScene=that._nameSpace.doc._scene;if(theScene){theScene.invalidateVolume();window.setTimeout(function(){that.invalidateVolume();theScene.updateVolume();that._nameSpace.doc.needRender=true;},1000);} that.appendAPI();that.fireEvents("load");} newScene=null;inlScene=null;xml=null;return xhr;};if(this._vf.url.length&&this._vf.url[0].length) {var xhrURI=this._nameSpace.getURL(this._vf.url[0]);xhr.open('GET',xhrURI,true);this._nameSpace.doc.incrementDownloads();try{x3dom.RequestManager.addRequest(xhr);} catch(ex){this.fireEvents("error");x3dom.debug.logError(this._vf.url[0]+": "+ex);}}}}));x3dom.registerNodeType("X3DBackgroundNode","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DBackgroundNode.superClass.call(this,ctx);var trans=(ctx&&ctx.autoGen)?1:0;this.addField_SFString(ctx,'crossOrigin','');this.addField_MFColor(ctx,'groundColor',[]);this.addField_MFFloat(ctx,'groundAngle',[]);this.addField_MFColor(ctx,'skyColor',[new x3dom.fields.SFColor(0,0,0)]);this.addField_MFFloat(ctx,'skyAngle',[]);this.addField_SFFloat(ctx,'transparency',trans);this._dirty=true;},{getSkyColor:function(){return new x3dom.fields.SFColor(0,0,0);},getTransparency:function(){return 0;},getTexUrl:function(){return[];}}));x3dom.registerNodeType("X3DFogNode","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DFogNode.superClass.call(this,ctx);this.addField_SFColor(ctx,'color',1,1,1);this.addField_SFString(ctx,'fogType',"LINEAR");this.addField_SFFloat(ctx,'visibilityRange',0);},{}));x3dom.registerNodeType("Fog","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DFogNode,function(ctx){x3dom.nodeTypes.Fog.superClass.call(this,ctx);},{}));x3dom.registerNodeType("Background","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBackgroundNode,function(ctx){x3dom.nodeTypes.Background.superClass.call(this,ctx);this.addField_MFString(ctx,'backUrl',[]);this.addField_MFString(ctx,'bottomUrl',[]);this.addField_MFString(ctx,'frontUrl',[]);this.addField_MFString(ctx,'leftUrl',[]);this.addField_MFString(ctx,'rightUrl',[]);this.addField_MFString(ctx,'topUrl',[]);this.addField_SFBool(ctx,'scaling',false);},{fieldChanged:function(fieldName) {if(fieldName.indexOf("Url")>0||fieldName=="transparency"||fieldName.search("sky")>=0||fieldName.search("ground")>=0){this._dirty=true;} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},getSkyColor:function(){return this._vf.skyColor;},getGroundColor:function(){return this._vf.groundColor;},getTransparency:function(){return this._vf.transparency;},getTexUrl:function(){return[this._nameSpace.getURL(this._vf.backUrl[0]),this._nameSpace.getURL(this._vf.frontUrl[0]),this._nameSpace.getURL(this._vf.bottomUrl[0]),this._nameSpace.getURL(this._vf.topUrl[0]),this._nameSpace.getURL(this._vf.leftUrl[0]),this._nameSpace.getURL(this._vf.rightUrl[0])];}}));x3dom.registerNodeType("X3DEnvironmentNode","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DEnvironmentNode.superClass.call(this,ctx);}));x3dom.registerNodeType("Environment","EnvironmentalEffects",defineClass(x3dom.nodeTypes.X3DEnvironmentNode,function(ctx){x3dom.nodeTypes.Environment.superClass.call(this,ctx);this.addField_SFBool(ctx,'sortTrans',true);this.addField_SFBool(ctx,'shadowExcludeTransparentObjects',false);this.addField_SFString(ctx,'gammaCorrectionDefault',"linear");this.addField_SFString(ctx,'tonemapping',"none");this.addField_SFBool(ctx,'frustumCulling',true);this.addField_SFBool(ctx,'smallFeatureCulling',false);this.addField_SFFloat(ctx,'smallFeatureThreshold',1.0);this.addField_SFBool(ctx,'occlusionCulling',false);this.addField_SFFloat(ctx,'occlusionVisibilityThreshold',0.0);this.addField_SFBool(ctx,'lowPriorityCulling',false);this.addField_SFFloat(ctx,'lowPriorityThreshold',1.0);this.addField_SFBool(ctx,'tessellationDetailCulling',false);this.addField_SFFloat(ctx,'tessellationErrorThreshold',0.0);this.addField_SFBool(ctx,'enableARC',false);this.addField_SFFloat(ctx,'minFrameRate',1.0);this.addField_SFFloat(ctx,'maxFrameRate',62.5);this.addField_SFFloat(ctx,'userDataFactor',-1);this.addField_SFFloat(ctx,'smallFeatureFactor',-1);this.addField_SFFloat(ctx,'occlusionVisibilityFactor',-1);this.addField_SFFloat(ctx,'lowPriorityFactor',-1);this.addField_SFFloat(ctx,'tessellationErrorFactor',-1);this.addField_SFBool(ctx,'SSAO',false);this.addField_SFFloat(ctx,'SSAOradius',0.7);this.addField_SFFloat(ctx,'SSAOamount',0.3);this.addField_SFInt32(ctx,'SSAOrandomTextureSize',4);this.addField_SFInt32(ctx,'SSAOblurDepthTreshold',1);this._validGammaCorrectionTypes=["none","fastlinear","linear"];this.checkSanity();},{checkSanity:function() {var checkParam=function(flag,value,defaultOn,defaultOff) {if(flag&&(value==defaultOff)) return defaultOn;if(!flag&&(value!=defaultOff)) return defaultOff;return value;};this._smallFeatureThreshold=checkParam(this._vf.smallFeatureCulling,this._vf.smallFeatureThreshold,10,0);this._lowPriorityThreshold=checkParam(this._vf.lowPriorityCulling,this._vf.lowPriorityThreshold,0.5,1);this._occlusionVisibilityThreshold=checkParam(this._vf.occlusionCulling,this._vf.occlusionVisibilityThreshold,1,0);this._tessellationErrorThreshold=checkParam(this._vf.tessellationDetailCulling,this._vf.tessellationErrorThreshold,1,0);var checkGamma=function(field,that){field=field.toLowerCase();if(that._validGammaCorrectionTypes.indexOf(field)>-1){return field;} else{x3dom.debug.logWarning(field+" gammaCorrectionDefault may only be linear (default), fastLinear, or none");return that._validGammaCorrectionTypes[0];}};this._vf.gammaCorrectionDefault=checkGamma(this._vf.gammaCorrectionDefault,this);}}));x3dom.registerNodeType("X3DViewpointNode","Navigation",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DViewpointNode.superClass.call(this,ctx);if(ctx&&ctx.xmlNode){var domNode=ctx.xmlNode;if(!domNode.resetView&&!domNode.getFieldOfView&&!domNode.getNear&&!domNode.getFar) {domNode.resetView=function(){var that=this._x3domNode;that.resetView();that._nameSpace.doc.needRender=true;};domNode.getFieldOfView=function(){return this._x3domNode.getFieldOfView();};domNode.getNear=function(){return this._x3domNode.getNear();};domNode.getFar=function(){return this._x3domNode.getFar();};}}},{activate:function(prev){var viewarea=this._nameSpace.doc._viewarea;if(prev&&this._bindAnimation){viewarea.animateTo(this,prev._autoGen?null:prev);} viewarea._needNavigationMatrixUpdate=true;x3dom.nodeTypes.X3DBindableNode.prototype.activate.call(this,prev);},deactivate:function(prev){x3dom.nodeTypes.X3DBindableNode.prototype.deactivate.call(this,prev);},getTransformation:function(){return this.getCurrentTransform();},getCenterOfRotation:function(){return new x3dom.fields.SFVec3f(0,0,0);},setCenterOfRotation:function(cor){this._vf.centerOfRotation.setValues(cor);},getFieldOfView:function(){return 1.57079633;},setView:function(newView){var mat=this.getCurrentTransform();this._viewMatrix=newView.mult(mat);},setViewAbsolute:function(newView) {this._viewMatrix=newView;},setProjectionMatrix:function(matrix) {},resetView:function(){},getNear:function(){return 0.1;},getFar:function(){return 10000;},getImgPlaneHeightAtDistOne:function(){return 2.0;},getViewMatrix:function(){return null;},getProjectionMatrix:function(aspect){return null;},setZoom:function(value){}}));x3dom.registerNodeType("Viewpoint","Navigation",defineClass(x3dom.nodeTypes.X3DViewpointNode,function(ctx){x3dom.nodeTypes.Viewpoint.superClass.call(this,ctx);this.addField_SFFloat(ctx,'fieldOfView',0.785398);this.addField_SFVec3f(ctx,'position',0,0,10);this.addField_SFRotation(ctx,'orientation',0,0,1,0);this.addField_SFVec3f(ctx,'centerOfRotation',0,0,0);this.addField_SFFloat(ctx,'zNear',-1);this.addField_SFFloat(ctx,'zFar',-1);this._viewMatrix=x3dom.fields.SFMatrix4f.translation(this._vf.position).mult(this._vf.orientation.toMatrix()).inverse();this._projMatrix=null;this._lastAspect=1.0;this._zRatio=10000;this._zNear=this._vf.zNear;this._zFar=this._vf.zFar;this._imgPlaneHeightAtDistOne=2.0*Math.tan(this._vf.fieldOfView/2.0);},{fieldChanged:function(fieldName){if(fieldName=="position"||fieldName=="orientation"){this.resetView();} else if(fieldName=="fieldOfView"||fieldName=="zNear"||fieldName=="zFar"){this._projMatrix=null;this._zNear=this._vf.zNear;this._zFar=this._vf.zFar;this._imgPlaneHeightAtDistOne=2.0*Math.tan(this._vf.fieldOfView/2.0);} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},setProjectionMatrix:function(matrix) {this._projMatrix=matrix;},getCenterOfRotation:function(){return this._vf.centerOfRotation;},getViewMatrix:function(){return this._viewMatrix;},getFieldOfView:function(){return this._vf.fieldOfView;},resetView:function(){this._viewMatrix=x3dom.fields.SFMatrix4f.translation(this._vf.position).mult(this._vf.orientation.toMatrix()).inverse();if(this._vf.isActive&&this._nameSpace&&this._nameSpace.doc._viewarea){this._nameSpace.doc._viewarea.resetNavHelpers();}},getNear:function(){return this._zNear;},getFar:function(){return this._zFar;},getImgPlaneHeightAtDistOne:function(){return this._imgPlaneHeightAtDistOne;},getProjectionMatrix:function(aspect) {var fovy=this._vf.fieldOfView;var zfar=this._vf.zFar;var znear=this._vf.zNear;if(znear<=0||zfar<=0) {var nearScale=0.8,farScale=1.2;var viewarea=this._nameSpace.doc._viewarea;var scene=viewarea._scene;var min=x3dom.fields.SFVec3f.copy(scene._lastMin);var max=x3dom.fields.SFVec3f.copy(scene._lastMax);var dia=max.subtract(min);var sRad=dia.length()/2;var mat=viewarea.getViewMatrix().inverse();var vp=mat.e3();var translation=new x3dom.fields.SFVec3f(0,0,0),scaleFactor=new x3dom.fields.SFVec3f(1,1,1);var rotation=new x3dom.fields.Quaternion(0,0,1,0),scaleOrientation=new x3dom.fields.Quaternion(0,0,1,0);mat.getTransform(translation,rotation,scaleFactor,scaleOrientation);var minScal=scaleFactor.x,maxScal=scaleFactor.x;if(maxScalscaleFactor.y)minScal=scaleFactor.y;if(maxScalscaleFactor.z)minScal=scaleFactor.z;if(maxScal>1) nearScale/=maxScal;else if(minScal>x3dom.fields.Eps&&minScal<1) farScale/=minScal;var sCenter=min.add(dia.multiply(0.5));var vDist=(vp.subtract(sCenter)).length();if(sRad){if(vDist>sRad) znear=(vDist-sRad)*nearScale;else znear=0;zfar=(vDist+sRad)*farScale;} else{znear=0.1;zfar=100000;} var zNearLimit=zfar/this._zRatio;znear=Math.max(znear,Math.max(x3dom.fields.Eps,zNearLimit));if(zfar>this._vf.zNear&&this._vf.zNear>0) znear=this._vf.zNear;if(this._vf.zFar>znear) zfar=this._vf.zFar;if(zfar<=znear) zfar=znear+1;} if(this._projMatrix==null) {this._projMatrix=x3dom.fields.SFMatrix4f.perspective(fovy,aspect,znear,zfar);} else if(this._zNear!=znear||this._zFar!=zfar) {var div=znear-zfar;this._projMatrix._22=(znear+zfar)/div;this._projMatrix._23=2*znear*zfar/div;} else if(this._lastAspect!=aspect) {this._projMatrix._00=(1/Math.tan(fovy/2))/aspect;this._lastAspect=aspect;} this._zNear=znear;this._zFar=zfar;return this._projMatrix;}}));x3dom.registerNodeType("OrthoViewpoint","Navigation",defineClass(x3dom.nodeTypes.X3DViewpointNode,function(ctx){x3dom.nodeTypes.OrthoViewpoint.superClass.call(this,ctx);this.addField_MFFloat(ctx,'fieldOfView',[-1,-1,1,1]);this.addField_SFVec3f(ctx,'position',0,0,10);this.addField_SFRotation(ctx,'orientation',0,0,0,1);this.addField_SFVec3f(ctx,'centerOfRotation',0,0,0);this.addField_SFFloat(ctx,'zNear',-1);this.addField_SFFloat(ctx,'zFar',-1);this._viewMatrix=null;this._projMatrix=null;this._lastAspect=1.0;this._zRatio=10000;this._zNear=this._vf.zNear;this._zFar=this._vf.zFar;this._fieldOfView=this._vf.fieldOfView.slice(0);this.resetView();},{fieldChanged:function(fieldName){if(fieldName=="position"||fieldName=="orientation"){this.resetView();} else if(fieldName=="fieldOfView") {this._fieldOfView=this._vf.fieldOfView;this._projMatrix=null;} else if(fieldName=="zNear"||fieldName=="zFar"){this._projMatrix=null;this.resetView();} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},getCenterOfRotation:function(){return this.getCurrentTransform().multMatrixPnt(this._vf.centerOfRotation);},getViewMatrix:function(){return this._viewMatrix;},resetView:function(){var offset=x3dom.fields.SFMatrix4f.translation(new x3dom.fields.SFVec3f((this._vf.fieldOfView[0]+this._vf.fieldOfView[2])/2,(this._vf.fieldOfView[1]+this._vf.fieldOfView[3])/2,0));this._viewMatrix=x3dom.fields.SFMatrix4f.translation(this._vf.position).mult(this._vf.orientation.toMatrix());this._viewMatrix=this._viewMatrix.inverse();this._projMatrix=null;if(this._vf.isActive&&this._nameSpace&&this._nameSpace.doc._viewarea){this._nameSpace.doc._viewarea.resetNavHelpers();}},getNear:function(){return this._vf.zNear;},getFar:function(){return this._vf.zFar;},getFieldOfView:function(){return 0.785;},setZoom:function(value){this._fieldOfView[0]=-value;this._fieldOfView[1]=-value;this._fieldOfView[2]=value;this._fieldOfView[3]=value;this._projMatrix=null;},getZoom:function(value){return this._fieldOfView;},getProjectionMatrix:function(aspect) {var fov=this.getFieldOfView();var zfar=this._vf.zFar;var znear=this._vf.zNear;if(znear<=0||zfar<=0) {var scene=this._nameSpace.doc._viewarea._scene;var min=x3dom.fields.SFVec3f.copy(scene._lastMin);var max=x3dom.fields.SFVec3f.copy(scene._lastMax);var dia=max.subtract(min);var tanfov2=Math.tan(fov/2.0);var dist1=((dia.y/2.0)/tanfov2+dia.z)+this._fieldOfView[2];var dist2=((dia.x/2.0)/tanfov2+dia.z)+this._fieldOfView[2];var dist=(dist1>dist2)?dist1:dist2;zfar=dist*4;znear=0.0001;this._viewMatrix._23=-(dist*2);} if(this._projMatrix==null||this._lastAspect!=aspect||this._zNear!=znear||this._zFar!=zfar) {var near=this._zNear=znear;var far=this._zFar=zfar;var left=this._fieldOfView[0];var bottom=this._fieldOfView[1];var right=this._fieldOfView[2];var top=this._fieldOfView[3];this._projMatrix=x3dom.fields.SFMatrix4f.ortho(left,right,bottom,top,near,far,aspect);} this._lastAspect=aspect;return this._projMatrix;}}));x3dom.registerNodeType("Viewfrustum","Navigation",defineClass(x3dom.nodeTypes.X3DViewpointNode,function(ctx){x3dom.nodeTypes.Viewfrustum.superClass.call(this,ctx);this.addField_SFMatrix4f(ctx,'modelview',1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);this.addField_SFMatrix4f(ctx,'projection',1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);this._viewMatrix=this._vf.modelview.transpose().inverse();this._projMatrix=this._vf.projection.transpose();this._centerOfRotation=new x3dom.fields.SFVec3f(0,0,0);},{fieldChanged:function(fieldName){if(fieldName=="modelview"){this.resetView();} else if(fieldName=="projection"){this._projMatrix=this._vf.projection.transpose();} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},getCenterOfRotation:function(){return this.getCurrentTransform().multMatrixPnt(this._centerOfRotation);},setCenterOfRotation:function(cor){this._centerOfRotation.setValues(cor);},getViewMatrix:function(){return this._viewMatrix;},getFieldOfView:function(){return(2.0*Math.atan(1.0/this._projMatrix._11));},getImgPlaneHeightAtDistOne:function(){return 2.0/this._projMatrix._11;},resetView:function(){this._viewMatrix=this._vf.modelview.transpose().inverse();this._centerOfRotation=new x3dom.fields.SFVec3f(0,0,0);},getProjectionMatrix:function(aspect){return this._projMatrix;}}));x3dom.registerNodeType("X3DNavigationInfoNode","Navigation",defineClass(x3dom.nodeTypes.X3DBindableNode,function(ctx){x3dom.nodeTypes.X3DNavigationInfoNode.superClass.call(this,ctx);}));x3dom.registerNodeType("NavigationInfo","Navigation",defineClass(x3dom.nodeTypes.X3DNavigationInfoNode,function(ctx){x3dom.nodeTypes.NavigationInfo.superClass.call(this,ctx);this.addField_SFBool(ctx,'headlight',true);this.addField_SFBool(ctx,'reverseScroll',false);this.addField_MFString(ctx,'type',["EXAMINE","ANY"]);this.addField_MFFloat(ctx,'typeParams',[-0.4,60,0.05,2.8]);this.addField_SFString(ctx,'explorationMode','all');this.addField_MFFloat(ctx,'avatarSize',[0.25,1.6,0.75]);this.addField_SFFloat(ctx,'walkDamping',2.0);this.addField_SFFloat(ctx,'visibilityLimit',0.0);this.addField_SFFloat(ctx,'speed',1.0);this.addField_SFTime(ctx,'transitionTime',1.0);this.addField_MFString(ctx,'transitionType',["LINEAR"]);this._validTypes=["none","examine","turntable","fly","freefly","lookat","lookaround","walk","game","helicopter","any"];this._typeMapping={"default":x3dom.DefaultNavigation,"turntable":x3dom.TurntableNavigation,"walk":x3dom.WalkNavigation};this._heliUpdated=false;var type=this.setType(this.getType());x3dom.debug.logInfo("NavType: "+type);},{fieldChanged:function(fieldName){if(fieldName=="typeParams"){this._heliUpdated=false;} else if(fieldName=="type"){this.setType(this.getType());} else if(fieldName.indexOf("bind")>=0){this.bind(this._vf.bind);}},setType:function(type,viewarea){var navType=this.checkType(type.toLowerCase());var oldType=this.checkType(this.getType());if(oldType!==navType||this._impl==null){if(this._typeMapping[navType]==null) this._impl=new this._typeMapping['default'](this);else this._impl=new this._typeMapping[navType](this);switch(navType){case'game':if(viewarea) viewarea.initMouseState();else this._nameSpace.doc._viewarea.initMouseState();break;case'helicopter':this._heliUpdated=false;break;case"turntable":if(viewarea){viewarea.initMouseState();} else if(this._nameSpace.doc._viewarea){this._nameSpace.doc._viewarea.initMouseState();} break;default:break;} if(this._nameSpace.doc._viewarea) this._impl.init(this._nameSpace.doc._viewarea,false);} this._vf.type[0]=navType;x3dom.debug.logInfo("Switch to "+navType+" mode.");},getType:function(){var type=this._vf.type[0].toLowerCase();if(type.length<=1) type="none";else if(type=="any") type="examine";return type;},getTypeParams:function(){var length=this._vf.typeParams.length;var theta=(length>=1)?this._vf.typeParams[0]:-0.4;var height=(length>=2)?this._vf.typeParams[1]:60.0;var minAngle=(length>=3)?this._vf.typeParams[2]:x3dom.fields.Eps;var maxAngle=(length>=4)?this._vf.typeParams[3]:Math.PI-x3dom.fields.Eps;var params=[theta,height,minAngle,maxAngle];if(length>=5) {params=params.concat(this._vf.typeParams.slice(4));} return params;},setTypeParams:function(params){for(var i=0;i-1){return type;} else{x3dom.debug.logWarning(type+" is no valid navigation type, use one of "+ this._validTypes.toString());return"examine";}},getExplorationMode:function(){switch(this._vf.explorationMode.toLowerCase()){case"all":return 7;case"rotate":return 1;case"zoom":return 2;case"pan":return 4;case"none":return 0;default:return 7;}}}));x3dom.registerNodeType("Billboard","Navigation",defineClass(x3dom.nodeTypes.X3DGroupingNode,function(ctx){x3dom.nodeTypes.Billboard.superClass.call(this,ctx);this.addField_SFVec3f(ctx,'axisOfRotation',0,1,0);this._eye=new x3dom.fields.SFVec3f(0,0,0);this._eyeViewUp=new x3dom.fields.SFVec3f(0,0,0);this._eyeLook=new x3dom.fields.SFVec3f(0,0,0);},{collectDrawableObjects:function(transform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes) {if(singlePath&&(this._parentNodes.length>1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<0){return;} singlePath=false;var vol=this.getVolume();var min=x3dom.fields.SFVec3f.MAX();var max=x3dom.fields.SFVec3f.MIN();vol.getBounds(min,max);var mat_view=drawableCollection.viewMatrix;var center=new x3dom.fields.SFVec3f(0,0,0);center=mat_view.inverse().multMatrixPnt(center);var mat_view_model=mat_view.mult(transform);this._eye=transform.inverse().multMatrixPnt(center);this._eyeViewUp=new x3dom.fields.SFVec3f(mat_view_model._10,mat_view_model._11,mat_view_model._12);this._eyeLook=new x3dom.fields.SFVec3f(mat_view_model._20,mat_view_model._21,mat_view_model._22);var rotMat=x3dom.fields.SFMatrix4f.identity();var mid=max.add(min).multiply(0.5);var billboard_to_viewer=this._eye.subtract(mid);if(this._vf.axisOfRotation.equals(new x3dom.fields.SFVec3f(0,0,0),x3dom.fields.Eps)){var rot1=x3dom.fields.Quaternion.rotateFromTo(billboard_to_viewer,new x3dom.fields.SFVec3f(0,0,1));rotMat=rot1.toMatrix().transpose();var yAxis=rotMat.multMatrixPnt(new x3dom.fields.SFVec3f(0,1,0)).normalize();var zAxis=rotMat.multMatrixPnt(new x3dom.fields.SFVec3f(0,0,1)).normalize();if(!this._eyeViewUp.equals(new x3dom.fields.SFVec3f(0,0,0),x3dom.fields.Eps)){var rot2=x3dom.fields.Quaternion.rotateFromTo(this._eyeLook,zAxis);var rotatedyAxis=rot2.toMatrix().transpose().multMatrixVec(yAxis);var rot3=x3dom.fields.Quaternion.rotateFromTo(this._eyeViewUp,rotatedyAxis);rotMat=rot2.toMatrix().transpose().mult(rotMat);rotMat=rot3.toMatrix().transpose().mult(rotMat);}} else{var normalPlane=this._vf.axisOfRotation.cross(billboard_to_viewer).normalize();if(this._eye.z<0){normalPlane=normalPlane.multiply(-1);} var degreesToRotate=Math.asin(normalPlane.dot(new x3dom.fields.SFVec3f(0,0,1)));if(this._eye.z<0){degreesToRotate+=Math.PI;} rotMat=x3dom.fields.SFMatrix4f.parseRotation(this._vf.axisOfRotation.x+", "+this._vf.axisOfRotation.y+", "+ this._vf.axisOfRotation.z+", "+degreesToRotate*(-1));} var childTransform=this.transformMatrix(transform.mult(rotMat));for(var i=0,i_n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<0){return;} var cnode,childTransform;if(singlePath){if(!this._graph.globalMatrix){this._graph.globalMatrix=this.transformMatrix(transform);} childTransform=this._graph.globalMatrix;} else{childTransform=this.transformMatrix(transform);} for(var i=0,n=this._childNodes.length;i1)) singlePath=false;if(singlePath&&(invalidateCache=invalidateCache||this.cacheInvalid())) this.invalidateCache();planeMask=drawableCollection.cull(transform,this.graphState(),singlePath,planeMask);if(planeMask<0){return;} singlePath=false;this.visitChildren(transform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes);},visitChildren:function(transform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes){}}));x3dom.registerNodeType("LOD","Navigation",defineClass(x3dom.nodeTypes.X3DLODNode,function(ctx){x3dom.nodeTypes.LOD.superClass.call(this,ctx);this.addField_MFFloat(ctx,"range",[]);this.addField_SFInt32(ctx,"level_changed",0);this._lastRangePos=-1;},{visitChildren:function(transform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes) {var i=0,n=this._childNodes.length;var mat_view=drawableCollection.viewMatrix;var center=new x3dom.fields.SFVec3f(0,0,0);center=mat_view.inverse().multMatrixPnt(center);this._eye=transform.inverse().multMatrixPnt(center);var len=this._vf.center.subtract(this._eye).length();while(ithis._vf.range[i]){i++;} if(i&&i>=n){i=n-1;} if(i!==this._lastRangePos){this.postMessage('level_changed',i);} this._lastRangePos=i;var cnode=this._childNodes[i];if(n&&cnode) {var childTransform=this.transformMatrix(transform);cnode.collectDrawableObjects(childTransform,drawableCollection,singlePath,invalidateCache,planeMask,clipPlanes);}},getVolume:function() {var vol=this._graph.volume;if(!this.volumeValid()&&this._vf.render) {var child,childVol;if(this._lastRangePos>=0){child=this._childNodes[this._lastRangePos];childVol=(child&&child._vf.render===true)?child.getVolume():null;if(childVol&&childVol.isValid()) vol.extendBounds(childVol.min,childVol.max);} else{for(var i=0,n=this._childNodes.length;ix3dom.fields.Eps&&len*this._vf.subScale<=this._vf.size.length()){if(this._childNodes.length<=1){var offset=new Array(new x3dom.fields.SFVec3f(-0.25*this._vf.size.x,0.25*this._vf.size.y,0),new x3dom.fields.SFVec3f(0.25*this._vf.size.x,0.25*this._vf.size.y,0),new x3dom.fields.SFVec3f(-0.25*this._vf.size.x,-0.25*this._vf.size.y,0),new x3dom.fields.SFVec3f(0.25*this._vf.size.x,-0.25*this._vf.size.y,0));for(l=0;l<4;l++){var node=new x3dom.nodeTypes.DynamicLOD();node._nameSpace=this._nameSpace;node._eye.setValues(this._eye);node.level=this.level+1;node.quadrant=l;node.cell=this.cell+l;node._vf.urlHead=this._vf.urlHead;node._vf.urlCenter=this._vf.urlCenter;node._vf.urlTail=this._vf.urlTail;node._vf.center=this._vf.center.add(offset[l]);node._vf.size=this._vf.size.multiply(0.5);node._vf.subdivision.setValues(this._vf.subdivision);var app=new x3dom.nodeTypes.Appearance();var tex=new x3dom.nodeTypes.ImageTexture();tex._nameSpace=this._nameSpace;tex._vf.url[0]=this._vf.urlHead+node.quadrant+this._vf.urlCenter+node.cell+this._vf.urlTail;app.addChild(tex);tex.nodeChanged();var shape=new x3dom.nodeTypes.Shape();shape._nameSpace=this._nameSpace;shape.addChild(app);app.nodeChanged();node.addChild(shape,"root");shape.nodeChanged();this.addChild(node);node.nodeChanged();}} else{for(l=1;l=6){var min=-navi._vf.typeParams[5];var max=navi._vf.typeParams[4];view._movement.z=Math.min(Math.max(view._movement.z,min),max);} view._movement=view._movement.add(vec);var mat=view.getViewpointMatrix().mult(view._transMat);view._transMat=mat.inverse().mult(x3dom.fields.SFMatrix4f.translation(view._movement)).mult(mat);}};x3dom.DefaultNavigation.prototype.moveForward=function(view) {var navi=this.navi;if(navi.getType()==="game") {var avatarRadius=0.25;if(navi._vf.avatarSize.length>2){avatarRadius=navi._vf.avatarSize[0];} var speed=5*view._deltaT*navi._vf.speed;var yRotRad=(view._yaw/180*Math.PI);var xRotRad=(view._pitch/180*Math.PI);var dist=0;var fMat=view._flyMat.inverse();view._scene._nameSpace.doc.ctx.pickValue(view,view._width/2,view._height/2,view._lastButton);if(view._pickingInfo.pickObj) {dist=view._pickingInfo.pickPos.subtract(fMat.e3()).length();if(dist<=2*avatarRadius){} else{view._eyePos.x-=Math.sin(yRotRad)*speed;view._eyePos.z+=Math.cos(yRotRad)*speed;view._eyePos.y+=Math.sin(xRotRad)*speed;}}}};x3dom.DefaultNavigation.prototype.moveBackwards=function(view) {var navi=this.navi;if(navi.getType()==="game") {var speed=5*view._deltaT*navi._vf.speed;var yRotRad=(view._yaw/180*Math.PI);var xRotRad=(view._pitch/180*Math.PI);view._eyePos.x+=Math.sin(yRotRad)*speed;view._eyePos.z-=Math.cos(yRotRad)*speed;view._eyePos.y-=Math.sin(xRotRad)*speed;}};x3dom.DefaultNavigation.prototype.strafeLeft=function(view) {var navi=this.navi;if(navi.getType()==="game") {var speed=5*view._deltaT*navi._vf.speed;var yRotRad=(view._yaw/180*Math.PI);view._eyePos.x+=Math.cos(yRotRad)*speed;view._eyePos.z+=Math.sin(yRotRad)*speed;}};x3dom.DefaultNavigation.prototype.strafeRight=function(view) {var navi=this.navi;if(navi.getType()==="game") {var speed=5*view._deltaT*navi._vf.speed;var yRotRad=(view._yaw/180*Math.PI);view._eyePos.x-=Math.cos(yRotRad)*speed;view._eyePos.z-=Math.sin(yRotRad)*speed;}};x3dom.DefaultNavigation.prototype.navigateTo=function(view,timeStamp) {var navi=this.navi;var navType=navi.getType();var savedPickingInfo=null;var needNavAnim=(view._currentInputType==x3dom.InputTypes.NAVIGATION)&&(navType==="game"||(view._lastButton>0&&(navType.indexOf("fly")>=0||navType==="walk"||navType==="helicopter"||navType.substr(0,5)==="looka")));view._deltaT=timeStamp-view._lastTS;var removeZeroMargin=function(val,offset){if(val>0){if(val<=offset){return 0;}else{return val-offset;}}else if(val<=0){if(val>=-offset){return 0;}else{return val+offset;}}};var humanizeDiff=function(scale,diff){return((diff<0)?-1:1)*Math.pow(scale*Math.abs(diff),1.65);};if(needNavAnim) {if(view._pickingInfo.pickObj!==null){savedPickingInfo={pickPos:view._pickingInfo.pickPos,pickNorm:view._pickingInfo.pickNorm,pickObj:view._pickingInfo.pickObj,firstObj:view._pickingInfo.firstObj,lastObj:view._pickingInfo.lastObj,lastClickObj:view._pickingInfo.lastClickObj,shadowObjectId:view._pickingInfo.shadowObjectId};} var avatarRadius=0.25;var avatarHeight=1.6;var avatarKnee=0.75;if(navi._vf.avatarSize.length>2){avatarRadius=navi._vf.avatarSize[0];avatarHeight=navi._vf.avatarSize[1];avatarKnee=navi._vf.avatarSize[2];} var currViewMat=view.getViewMatrix();var dist=0;var screenSize=Math.min(view._width,view._height);var rdeltaX=removeZeroMargin((view._pressX-view._lastX)/screenSize,0.01);var rdeltaY=removeZeroMargin((view._pressY-view._lastY)/screenSize,0.01);var userXdiff=humanizeDiff(1,rdeltaX);var userYdiff=humanizeDiff(1,rdeltaY);var step=(view._lastButton&2)?-1:1;step*=(view._deltaT*navi._vf.speed);var userXstep=view._deltaT*navi._vf.speed*userXdiff;var userYstep=view._deltaT*navi._vf.speed*userYdiff;var phi=Math.PI*view._deltaT*userXdiff;var theta=Math.PI*view._deltaT*userYdiff;if(view._needNavigationMatrixUpdate===true) {view._needNavigationMatrixUpdate=false;view._rotMat=x3dom.fields.SFMatrix4f.identity();view._transMat=x3dom.fields.SFMatrix4f.identity();view._movement=new x3dom.fields.SFVec3f(0,0,0);var angleX=0;var angleY=Math.asin(currViewMat._02);var C=Math.cos(angleY);if(Math.abs(C)>0.0001){angleX=Math.atan2(-currViewMat._12/C,currViewMat._22/C);} view._flyMat=currViewMat.inverse();view._from=view._flyMat.e3();view._at=view._from.subtract(view._flyMat.e2());if(navType==="helicopter") view._at.y=view._from.y;view._up=view._flyMat.e1();view._pitch=angleX*180/Math.PI;view._yaw=angleY*180/Math.PI;view._eyePos=view._from.negate();} var tmpAt=null,tmpUp=null,tmpMat=null;var q,temp,fin;var lv,sv,up;if(navType==="game") {view._pitch+=view._dy;view._yaw+=view._dx;if(view._pitch>=89)view._pitch=89;if(view._pitch<=-89)view._pitch=-89;if(view._yaw>=360)view._yaw-=360;if(view._yaw<0)view._yaw=360+view._yaw;view._dx=0;view._dy=0;var xMat=x3dom.fields.SFMatrix4f.rotationX(view._pitch/180*Math.PI);var yMat=x3dom.fields.SFMatrix4f.rotationY(view._yaw/180*Math.PI);var fPos=x3dom.fields.SFMatrix4f.translation(view._eyePos);view._flyMat=xMat.mult(yMat).mult(fPos);var flyMat=view._flyMat.inverse();var tmpFrom=flyMat.e3();tmpUp=new x3dom.fields.SFVec3f(0,-1,0);tmpAt=tmpFrom.add(tmpUp);tmpUp=flyMat.e0().cross(tmpUp).normalize();tmpMat=x3dom.fields.SFMatrix4f.lookAt(tmpFrom,tmpAt,tmpUp);tmpMat=tmpMat.inverse();view._scene._nameSpace.doc.ctx.pickValue(view,view._width/2,view._height/2,view._lastButton,tmpMat,view.getProjectionMatrix().mult(tmpMat));if(view._pickingInfo.pickObj) {dist=view._pickingInfo.pickPos.subtract(tmpFrom).length();tmpFrom.y+=(avatarHeight-dist);flyMat.setTranslate(tmpFrom);view._eyePos=flyMat.e3().negate();view._flyMat=flyMat.inverse();view._pickingInfo.pickObj=null;} view._scene.getViewpoint().setView(view._flyMat);return needNavAnim;} else if(navType==="helicopter"){var typeParams=navi.getTypeParams();if(view._lastButton&2) {var stepUp=200*userYstep;typeParams[1]+=stepUp;navi.setTypeParams(typeParams);} if(view._lastButton&1){step=300*userYstep;} else{step=0;} theta=typeParams[0];view._from.y=typeParams[1];view._at.y=view._from.y;q=x3dom.fields.Quaternion.axisAngle(view._up,phi);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(view._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(view._from.negate());fin=fin.mult(temp);view._at=fin.multMatrixPnt(view._at);lv=view._at.subtract(view._from).normalize();sv=lv.cross(view._up).normalize();up=sv.cross(lv).normalize();lv=lv.multiply(step);view._from=view._from.add(lv);view._at=view._at.add(lv);q=x3dom.fields.Quaternion.axisAngle(sv,theta);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(view._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(view._from.negate());fin=fin.mult(temp);var at=fin.multMatrixPnt(view._at);view._flyMat=x3dom.fields.SFMatrix4f.lookAt(view._from,at,up);view._scene.getViewpoint().setView(view._flyMat.inverse());return needNavAnim;} q=x3dom.fields.Quaternion.axisAngle(view._up,phi);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(view._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(view._from.negate());fin=fin.mult(temp);view._at=fin.multMatrixPnt(view._at);lv=view._at.subtract(view._from).normalize();sv=lv.cross(view._up).normalize();up=sv.cross(lv).normalize();q=x3dom.fields.Quaternion.axisAngle(sv,theta);temp=q.toMatrix();fin=x3dom.fields.SFMatrix4f.translation(view._from);fin=fin.mult(temp);temp=x3dom.fields.SFMatrix4f.translation(view._from.negate());fin=fin.mult(temp);view._at=fin.multMatrixPnt(view._at);if(navType.substr(0,5)!=="looka") {var currProjMat=view.getProjectionMatrix();if(navType!=="freefly"){if(step<0){tmpMat=new x3dom.fields.SFMatrix4f();tmpMat.setValue(view._last_mat_view.e0(),view._last_mat_view.e1(),view._last_mat_view.e2().negate(),view._last_mat_view.e3());view._scene._nameSpace.doc.ctx.pickValue(view,view._width/2,view._height/2,view._lastButton,tmpMat,currProjMat.mult(tmpMat));} else{view._scene._nameSpace.doc.ctx.pickValue(view,view._width/2,view._height/2,view._lastButton);} if(view._pickingInfo.pickObj) {dist=view._pickingInfo.pickPos.subtract(view._from).length();if(dist<=avatarRadius){step=0;}}} lv=view._at.subtract(view._from).normalize().multiply(step);view._at=view._at.add(lv);view._from=view._from.add(lv);if(navType==="walk") {up.x=0.0;up.y=1.0;up.z=0.0;tmpAt=view._from.addScaled(up,-1.0);tmpUp=sv.cross(up.negate()).normalize();tmpMat=x3dom.fields.SFMatrix4f.lookAt(view._from,tmpAt,tmpUp);tmpMat=tmpMat.inverse();view._scene._nameSpace.doc.ctx.pickValue(view,view._width/2,view._height/2,view._lastButton,tmpMat,currProjMat.mult(tmpMat));if(view._pickingInfo.pickObj) {dist=view._pickingInfo.pickPos.subtract(view._from).length();dist=(avatarHeight-dist)/navi._vf.walkDamping;view._at=view._at.add(up.multiply(dist));view._from=view._from.add(up.multiply(dist));}} view._pickingInfo.pickObj=null;} view._flyMat=x3dom.fields.SFMatrix4f.lookAt(view._from,view._at,up);view._scene.getViewpoint().setView(view._flyMat.inverse());if(savedPickingInfo!==null){view._pickingInfo=savedPickingInfo;}} return needNavAnim;};x3dom.DefaultNavigation.prototype.animateTo=function(view,target,prev,dur) {var navi=this.navi;var prevTargetMat;var prevMat;if(x3dom.isa(target,x3dom.nodeTypes.X3DViewpointNode)) {target=target.getViewMatrix().mult(target.getCurrentTransform().inverse());} if(navi._vf.transitionType[0].toLowerCase()!=="teleport"&&dur!=0&&navi.getType()!=="game") {if(prev&&x3dom.isa(prev,x3dom.nodeTypes.X3DViewpointNode)) {prevMat=prev.getViewMatrix().mult(prev.getCurrentTransform().inverse()).mult(view._transMat).mult(view._rotMat);if(view._mixer.isActive()) {prev.setView(view._mixer.getEndMatrix());view._mixer.reset();} view._mixer.beginTime=view._lastTS;if(arguments.length>=4&&arguments[3]!=null) {view._mixer.endTime=view._lastTS+dur;} else {view._mixer.endTime=view._lastTS+navi._vf.transitionTime;} view._mixer.setBeginMatrix(prevMat);view._mixer.setEndMatrix(target);view._scene.getViewpoint().setView(prevMat);} else {view._scene.getViewpoint().setView(target);}} else {view._scene.getViewpoint().setView(target);} view._rotMat=x3dom.fields.SFMatrix4f.identity();view._transMat=x3dom.fields.SFMatrix4f.identity();view._movement=new x3dom.fields.SFVec3f(0,0,0);view._needNavigationMatrixUpdate=true;};x3dom.DefaultNavigation.prototype.orthoAnimateTo=function(view,target,prev,duration) {var navi=this.navi;duration=duration||navi._vf.transitionTime;view._interpolator.beginValue=prev;view._interpolator.endValue=target;view._interpolator.beginTime=view._lastTS;view._interpolator.endTime=view._lastTS+duration;};x3dom.DefaultNavigation.prototype.resetView=function(view) {var navi=this.navi;if(navi._vf.transitionType[0].toLowerCase()!=="teleport"&&navi.getType()!=="game") {var viewpoint=view._scene.getViewpoint();view._mixer.beginTime=view._lastTS;view._mixer.endTime=view._lastTS+navi._vf.transitionTime;view._mixer.setBeginMatrix(view.getViewMatrix());if(x3dom.isa(viewpoint,x3dom.nodeTypes.OrthoViewpoint)) {this.orthoAnimateTo(view,Math.abs(viewpoint._vf.fieldOfView[0]),Math.abs(viewpoint._fieldOfView[0]));} var target=view._scene.getViewpoint();target.resetView();target=target.getViewMatrix().mult(target.getCurrentTransform().inverse());view._mixer.setEndMatrix(target);} else {view._scene.getViewpoint().resetView();} view.resetNavHelpers();navi._heliUpdated=false;};x3dom.DefaultNavigation.prototype.onDrag=function(view,x,y,buttonState) {var navi=this.navi;var navType=navi.getType();var navRestrict=navi.getExplorationMode();if(navType==="none"||navRestrict==0){return;} var viewpoint=view._scene.getViewpoint();var dx=x-view._lastX;var dy=y-view._lastY;view._dx=dx;view._dy=dy;view._lastX=x;view._lastY=y;if(navType!=="examine"){return;} var d,vec,cor,mat=null;var alpha,beta;buttonState=buttonState&navRestrict;if(buttonState&1) {alpha=(dy*2*Math.PI)/view._width;beta=(dx*2*Math.PI)/view._height;mat=view.getViewMatrix();var mx=x3dom.fields.SFMatrix4f.rotationX(alpha);var my=x3dom.fields.SFMatrix4f.rotationY(beta);var center=viewpoint.getCenterOfRotation();mat.setTranslate(new x3dom.fields.SFVec3f(0,0,0));view._rotMat=view._rotMat.mult(x3dom.fields.SFMatrix4f.translation(center)).mult(mat.inverse()).mult(mx).mult(my).mult(mat).mult(x3dom.fields.SFMatrix4f.translation(center.negate()));} if(buttonState&4) {d=(view._scene._lastMax.subtract(view._scene._lastMin)).length();d=Math.min(d,viewpoint.getFar());d=((d=6){var min=-navi._vf.typeParams[5];var max=navi._vf.typeParams[4];view._movement.z=Math.min(Math.max(view._movement.z,min),max);} view._movement=view._movement.add(vec);mat=view.getViewpointMatrix().mult(view._transMat);view._transMat=mat.inverse().mult(x3dom.fields.SFMatrix4f.translation(view._movement)).mult(mat);}} view._isMoving=true;};x3dom.DefaultNavigation.prototype.onTouchStart=function(view,evt,touches) {};x3dom.DefaultNavigation.prototype.onTouchDrag=function(view,evt,touches,translation,rotation) {if(view._currentInputType==x3dom.InputTypes.NAVIGATION) {var navi=this.navi;var viewpoint=view._scene.getViewpoint();var navRestrict=navi.getExplorationMode();if(navi.getType()==="examine"&&navRestrict!==0) {if(translation&&navRestrict&4) {var distance=(view._scene._lastMax.subtract(view._scene._lastMin)).length();distance=Math.min(distance,viewpoint.getFar());distance=((distancebbox.max.y||cor.ybbox.max.x||cor.x0&&phinavi._vf.typeParams[5])phi=navi._vf.typeParams[4];else if(beta<0&&phi>navi._vf.typeParams[5]&&phi=4&&arguments[3]!=null){view._mixer.endTime=view._lastTS+dur;} else{view._mixer.endTime=view._lastTS+navi._vf.transitionTime;} view._mixer.setBeginMatrix(prev);view._mixer.setEndMatrix(targetMat);view._scene.getViewpoint().setViewAbsolute(prev);} else if(prev){view._mixer.beginTime=view._lastTS;if(arguments.length>=4&&arguments[3]!=null){view._mixer.endTime=view._lastTS+dur;} else{view._mixer.endTime=view._lastTS+navi._vf.transitionTime;} view._mixer.setBeginMatrix(prev);view._mixer.setEndMatrix(targetMat);view._scene.getViewpoint().setViewAbsolute(prev);}else{view._scene.getViewpoint().setViewAbsolute(targetMat);}} else {view._scene.getViewpoint().setViewAbsolute(target);} view._rotMat=x3dom.fields.SFMatrix4f.identity();view._transMat=x3dom.fields.SFMatrix4f.identity();view._movement=new x3dom.fields.SFVec3f(0,0,0);view._needNavigationMatrixUpdate=true;this.updateFlyMat(view,target,targetMat);};x3dom.TurntableNavigation.prototype.onTouchStart=function(view,evt,touches) {view._numTouches=evt.touches.length;view._lastX=evt.touches[0].screenX;view._lastY=evt.touches[0].screenY;};x3dom.TurntableNavigation.prototype.onTouchDrag=function(view,evt,touches,translation,rotation) {if(view._currentInputType==x3dom.InputTypes.NAVIGATION) {if(evt.touches.length==1) {var dx=(evt.touches[0].screenX-view._lastX);var dy=(evt.touches[0].screenY-view._lastY);var alpha=(dy*2*Math.PI)/view._height;var beta=(dx*2*Math.PI)/view._width;this.rotate(view,alpha,beta);view._lastX=evt.touches[0].screenX;view._lastY=evt.touches[0].screenY;} else if(evt.touches.length>=2) {if(this.panEnabled==true) this.pan(view,-translation.x*4.0,-translation.y*4.0);this.zoom(view,translation.z*4.0);}}};x3dom.TurntableNavigation.prototype.onTouchEnd=function(view,evt,touches) {if(view._numTouches==2&&evt.touches.length==1){view._lastX=evt.touches[0].screenX;view._lastY=evt.touches[0].screenY;} view._numTouches=evt.touches.length;};x3dom.TurntableNavigation.prototype.setPanTarget=function(target) {this.target=target;};x3dom.TurntableNavigation.prototype.setPanAxis=function(a,b) {this.panAxisX=a;this.panAxisY=b;};x3dom.TurntableNavigation.prototype.setPanEnabled=function(enabled) {this.panEnabled=enabled;};x3dom.TurntableNavigation.prototype.onDoubleClick=function(view,x,y) {if(view._doc._x3dElem.hasAttribute('disableDoubleClick')&&view._doc._x3dElem.getAttribute('disableDoubleClick')==='true'){return;} var navi=view._scene.getNavigationInfo();if(navi.getType()=="none"){return;} var pickMode=view._scene._vf.pickMode.toLowerCase();if((pickMode=="color"||pickMode=="texcoord")){return;} var viewpoint=view._scene.getViewpoint();viewpoint.setCenterOfRotation(view._pick);x3dom.debug.logInfo("New center of Rotation: "+view._pick);var mat=view.getViewMatrix().inverse();view._from=mat.e3();view._up=mat.e1();view._at=view._pick;view._flyMat=x3dom.fields.SFMatrix4f.lookAt(view._from,view._at,view._up);var offset=view._from.subtract(view._at);var phi=Math.atan2(offset.x,offset.z);var theta=Math.atan2(Math.sqrt(offset.x*offset.x+offset.z*offset.z),offset.y);view._flyMat=this.calcOrbit(view,theta,phi,true);x3dom.debug.logInfo("New camera position: "+view._from);this.animateTo(view,view._flyMat.inverse(),view.getViewMatrix());};x3dom.WalkNavigation=function(navigationNode) {x3dom.DefaultNavigation.call(this,navigationNode);};x3dom.WalkNavigation.prototype=Object.create(x3dom.DefaultNavigation.prototype);x3dom.WalkNavigation.prototype.constructor=x3dom.WalkNavigation;x3dom.WalkNavigation.prototype.onDrag=function(view,x,y,buttonState) {var navi=this.navi;var navType=navi.getType();var navRestrict=navi.getExplorationMode();if(navRestrict===0){return;} var viewpoint=view._scene.getViewpoint();var dx=x-view._lastX;var dy=y-view._lastY;view._dx=dx;view._dy=dy;view._lastX=x;view._lastY=y;if(navType==="walk"){return;} console.log("#### CHECK: in WalkNavigation but nav. type is not walk !");};x3dom.registerNodeType("X3DFontStyleNode","Text",defineClass(x3dom.nodeTypes.X3DNode,function(ctx){x3dom.nodeTypes.X3DFontStyleNode.superClass.call(this,ctx);}));x3dom.registerNodeType("FontStyle","Text",defineClass(x3dom.nodeTypes.X3DFontStyleNode,function(ctx){x3dom.nodeTypes.FontStyle.superClass.call(this,ctx);this.addField_MFString(ctx,'family',['SERIF']);this.addField_SFBool(ctx,'horizontal',true);this.addField_MFString(ctx,'justify',['MIDDLE','MIDDLE']);this.addField_SFString(ctx,'language',"");this.addField_SFBool(ctx,'leftToRight',true);this.addField_SFFloat(ctx,'size',1.0);this.addField_SFFloat(ctx,'spacing',1.0);this.addField_SFString(ctx,'style',"PLAIN");this.addField_SFBool(ctx,'topToBottom',true);this.addField_SFFloat(ctx,'quality',2.0);},{fieldChanged:function(fieldName){if(fieldName=='family'||fieldName=='horizontal'||fieldName=='justify'||fieldName=='language'||fieldName=='leftToRight'||fieldName=='size'||fieldName=='spacing'||fieldName=='style'||fieldName=='topToBottom'){Array.forEach(this._parentNodes,function(node){Array.forEach(node._parentNodes,function(textnode){textnode.setAllDirty();});});}}}));x3dom.nodeTypes.FontStyle.defaultNode=function(){if(!x3dom.nodeTypes.FontStyle._defaultNode){x3dom.nodeTypes.FontStyle._defaultNode=new x3dom.nodeTypes.FontStyle();x3dom.nodeTypes.FontStyle._defaultNode.nodeChanged();} return x3dom.nodeTypes.FontStyle._defaultNode;};x3dom.registerNodeType("Text","Text",defineClass(x3dom.nodeTypes.X3DGeometryNode,function(ctx){x3dom.nodeTypes.Text.superClass.call(this,ctx);this.addField_MFString(ctx,'string',[]);this.addField_MFFloat(ctx,'length',[]);this.addField_SFFloat(ctx,'maxExtent',0.0);this.addField_SFNode('fontStyle',x3dom.nodeTypes.X3DFontStyleNode);this._mesh._positions[0]=[0,0,0,1,0,0,1,1,0,0,1,0];this._mesh._normals[0]=[0,0,1,0,0,1,0,0,1,0,0,1];this._mesh._texCoords[0]=[0,0,1,0,1,1,0,1];this._mesh._colors[0]=[];this._mesh._indices[0]=[0,1,2,2,3,0];this._mesh._invalidate=true;this._mesh._numFaces=2;this._mesh._numCoords=4;},{nodeChanged:function(){if(!this._cf.fontStyle.node){this.addChild(x3dom.nodeTypes.FontStyle.defaultNode());} this.invalidateVolume();},fieldChanged:function(fieldName){if(fieldName=='string'||fieldName=='length'||fieldName=='maxExtent'){this.invalidateVolume();Array.forEach(this._parentNodes,function(node){node.setAllDirty();});}},validateGLObject:function() {Array.forEach(this._parentNodes,function(node){node._dirty.texture=false;});this._nameSpace.doc.needRender=true;}}));x3dom.registerNodeType("X3DSoundNode","Sound",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DSoundNode.superClass.call(this,ctx);}));x3dom.registerNodeType("Sound","Sound",defineClass(x3dom.nodeTypes.X3DSoundNode,function(ctx){x3dom.nodeTypes.Sound.superClass.call(this,ctx);this.addField_SFNode('source',x3dom.nodeTypes.X3DSoundSourceNode);},{nodeChanged:function() {if(this._cf.source.node||!this._xmlNode){return;} x3dom.debug.logInfo("No AudioClip child node given, searching for <audio> elements...");try{Array.forEach(this._xmlNode.childNodes,function(childDomNode){if(childDomNode.nodeType===1) {x3dom.debug.logInfo("### Found <"+childDomNode.nodeName+"> tag.");if(childDomNode.localName.toLowerCase()==="audio") {var loop=childDomNode.getAttribute("loop");loop=loop?(loop.toLowerCase()==="loop"):false;var newNode=childDomNode.cloneNode(false);childDomNode.parentNode.removeChild(childDomNode);childDomNode=null;if(navigator.appName!="Microsoft Internet Explorer"){document.body.appendChild(newNode);} var startAudio=function(){newNode.play();};var audioDone=function(){if(loop){newNode.play();}};newNode.addEventListener("canplaythrough",startAudio,true);newNode.addEventListener("ended",audioDone,true);}}});} catch(e){x3dom.debug.logException(e);}}}));x3dom.registerNodeType("X3DSoundSourceNode","Sound",defineClass(x3dom.nodeTypes.X3DTimeDependentNode,function(ctx){x3dom.nodeTypes.X3DSoundSourceNode.superClass.call(this,ctx);}));x3dom.registerNodeType("AudioClip","Sound",defineClass(x3dom.nodeTypes.X3DSoundSourceNode,function(ctx){x3dom.nodeTypes.AudioClip.superClass.call(this,ctx);this.addField_MFString(ctx,'url',[]);this.addField_SFBool(ctx,'enabled',false);this.addField_SFBool(ctx,'loop',false);this._audio=document.createElement('audio');if(navigator.appName!="Microsoft Internet Explorer"){document.body.appendChild(this._audio);} this._sources=[];},{nodeChanged:function() {this._createSources=function() {this._sources=[];for(var i=0;i=0&&pos=3,"RenderedTexture.dimensions requires at least 3 entries.");this._clearParents=true;this._needRenderUpdate=true;this.checkDepthTextureSupport=function(){if(this._vf.depthMap&&x3dom.caps.DEPTH_TEXTURE===null) x3dom.debug.logWarning("RenderedTexture Node: depth texture extension not supported");};this.checkDepthTextureSupport();},{nodeChanged:function() {this._clearParents=true;this._needRenderUpdate=true;},fieldChanged:function(fieldName) {switch(fieldName) {case"excludeNodes":this._clearParents=true;break;case"update":if(this._vf.update.toUpperCase()=="NEXT_FRAME_ONLY"||this._vf.update.toUpperCase()=="ALWAYS"){this._needRenderUpdate=true;} break;case"depthMap":this.checkDepthTextureSupport();this._x3domTexture.updateTexture();this._needRenderUpdate=true;default:break;}},getViewMatrix:function() {if(this._clearParents&&this._cf.excludeNodes.nodes.length){var that=this;Array.forEach(this._cf.excludeNodes.nodes,function(node){for(var i=0,n=node._parentNodes.length;i11)?11:this._vf.iterations;this._vf.iterations=(this._vf.iterations<3)?3:this._vf.iterations;this._vf.maxLevel=(this._vf.maxLevel>11)?11:this._vf.maxLevel;this._vf.maxLevel=(this._vf.maxLevel<3)?3:this._vf.maxLevel;this._vf.maxLevel=(this._vf.maxLevel>this._vf.iterations)?this._vf.iterations:this._vf.maxLevel;var repeatConfig=[{x:4,y:8},{x:8,y:8},{x:8,y:16},{x:16,y:16},{x:16,y:32},{x:32,y:32},{x:32,y:64},{x:64,y:64},{x:64,y:128}];this._repeat=new x3dom.fields.SFVec2f(this._vf.dimensions[0]/repeatConfig[this._vf.iterations-3].x,this._vf.dimensions[1]/repeatConfig[this._vf.iterations-3].y);this._renderedImage=0;this._currLoadLevel=0;this._loadLevel=1;},{nextLevel:function(){if(this._loadLevel"+"http://x3dom.org/x3dom/doc/help/composedShader.html)\n"+" attribute vec3 position;\n"+" attribute vec3 normal;\n"+" attribute vec2 texcoord;\n"+" attribute vec3 color;\n"+" uniform mat4 modelViewProjectionMatrix;\n"+" uniform mat4 modelViewMatrix;\n"+" uniform mat4 normalMatrix;\n"+" uniform mat4 viewMatrix;\n"+" uniform sampler2D tex;\n");x3dom.nodeTypes.ComposedShader.ShaderInfoMsgShown=true;}},{nodeChanged:function() {var i,n=this._cf.parts.nodes.length;for(i=0;itwoPi) this._vf.angle=twoPi;this._origCCW=this._vf.ccw;var innerRadius=this._vf.innerRadius;var outerRadius=this._vf.outerRadius;if(this._vf.insideOutsideRadius==true) {if(innerRadius>outerRadius){var tmp=innerRadius;innerRadius=outerRadius;outerRadius=tmp;} var rad=(outerRadius-innerRadius)/2;outerRadius=innerRadius+rad;innerRadius=rad;this._vf.ccw=!this._origCCW;} var rings=this._vf.subdivision.x,sides=this._vf.subdivision.y;rings=Math.max(3,Math.round((this._vf.angle/twoPi)*rings));var geoCacheID='Torus_'+innerRadius+'_'+outerRadius+'_'+this._vf.angle+'_'+ this._vf.subdivision+'-'+this._vf.caps;if(this._vf.useGeoCache&&x3dom.geoCache[geoCacheID]!==undefined) {this._mesh=x3dom.geoCache[geoCacheID];} else {var ringDelta=this._vf.angle/rings;var sideDelta=twoPi/sides;var a,b,theta,phi;var cosTheta,sinTheta,cosPhi,sinPhi,dist;for(a=0,theta=0;a<=rings;a++,theta+=ringDelta) {cosTheta=Math.cos(theta);sinTheta=Math.sin(theta);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,innerRadius*sinPhi,-sinTheta*dist);this._mesh._normals[0].push(cosTheta*cosPhi,sinPhi,-sinTheta*cosPhi);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,innerRadius*sinPhi);this._mesh._normals[0].push(cosTheta*cosPhi,-sinTheta*cosPhi,sinPhi);} this._mesh._texCoords[0].push(-a/rings,b/sides);}} for(a=0;a0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+b-1);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+1);this._mesh._indices[0].push(origPos+b);}} cosTheta=Math.cos(this._vf.angle);sinTheta=Math.sin(this._vf.angle);origPos=this._mesh._positions[0].length/3;var nx=-sinTheta,ny=-cosTheta;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*outerRadius,0,-sinTheta*outerRadius);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*outerRadius,-sinTheta*outerRadius,0);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(0.5,0.5);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,sinPhi*innerRadius,-sinTheta*dist);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,sinPhi*innerRadius);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(1-(1+cosPhi)*0.5,(1-sinPhi)*0.5);if(b>0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b-1);this._mesh._indices[0].push(origPos+b);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+1);}}} this._mesh._invalidate=true;this._mesh._numFaces=this._mesh._indices[0].length/3;this._mesh._numCoords=this._mesh._positions[0].length/3;x3dom.geoCache[geoCacheID]=this._mesh;}},{fieldChanged:function(fieldName) {if(fieldName=="innerRadius"||fieldName=="outerRadius"||fieldName=="subdivision"||fieldName=="angle"||fieldName=="insideOutsideRadius"||fieldName=="caps") {var twoPi=2.0*Math.PI;if(this._vf.angle<0) this._vf.angle=0;else if(this._vf.angle>twoPi) this._vf.angle=twoPi;var innerRadius=this._vf.innerRadius;var outerRadius=this._vf.outerRadius;if(this._vf.insideOutsideRadius==true) {if(innerRadius>outerRadius){var tmp=innerRadius;innerRadius=outerRadius;outerRadius=tmp;} var rad=(outerRadius-innerRadius)/2;outerRadius=innerRadius+rad;innerRadius=rad;this._vf.ccw=!this._origCCW;} else this._vf.ccw=this._origCCW;var rings=this._vf.subdivision.x,sides=this._vf.subdivision.y;rings=Math.max(3,Math.round((this._vf.angle/twoPi)*rings));var ringDelta=this._vf.angle/rings;var sideDelta=twoPi/sides;var a,b,theta,phi;var cosTheta,sinTheta,cosPhi,sinPhi,dist;this._mesh._positions[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];this._mesh._indices[0]=[];for(a=0,theta=0;a<=rings;a++,theta+=ringDelta) {cosTheta=Math.cos(theta);sinTheta=Math.sin(theta);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,innerRadius*sinPhi,-sinTheta*dist);this._mesh._normals[0].push(cosTheta*cosPhi,sinPhi,-sinTheta*cosPhi);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,innerRadius*sinPhi);this._mesh._normals[0].push(cosTheta*cosPhi,-sinTheta*cosPhi,sinPhi);} this._mesh._texCoords[0].push(-a/rings,b/sides);}} for(a=0;a0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+b-1);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+1);this._mesh._indices[0].push(origPos+b);}} cosTheta=Math.cos(this._vf.angle);sinTheta=Math.sin(this._vf.angle);origPos=this._mesh._positions[0].length/3;var nx=-sinTheta,ny=-cosTheta;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*outerRadius,0,-sinTheta*outerRadius);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*outerRadius,-sinTheta*outerRadius,0);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(0.5,0.5);for(b=0,phi=0;b<=sides;b++,phi+=sideDelta) {cosPhi=Math.cos(phi);sinPhi=Math.sin(phi);dist=outerRadius+innerRadius*cosPhi;if(this._vf.insideOutsideRadius){this._mesh._positions[0].push(cosTheta*dist,sinPhi*innerRadius,-sinTheta*dist);this._mesh._normals[0].push(nx,0,ny);} else{this._mesh._positions[0].push(cosTheta*dist,-sinTheta*dist,sinPhi*innerRadius);this._mesh._normals[0].push(nx,ny,0);} this._mesh._texCoords[0].push(1-(1+cosPhi)*0.5,(1-sinPhi)*0.5);if(b>0){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b-1);this._mesh._indices[0].push(origPos+b);} if(b==sides){this._mesh._indices[0].push(origPos);this._mesh._indices[0].push(origPos+b);this._mesh._indices[0].push(origPos+1);}}} this.invalidateVolume();this._mesh._numFaces=this._mesh._indices[0].length/3;this._mesh._numCoords=this._mesh._positions[0].length/3;Array.forEach(this._parentNodes,function(node){node.setAllDirty();node.invalidateVolume();});}}}));x3dom.registerNodeType("Cone","Geometry3D",defineClass(x3dom.nodeTypes.X3DSpatialGeometryNode,function(ctx){x3dom.nodeTypes.Cone.superClass.call(this,ctx);this.addField_SFFloat(ctx,'bottomRadius',1.0);this.addField_SFFloat(ctx,'topRadius',0);this.addField_SFFloat(ctx,'height',2.0);this.addField_SFBool(ctx,'bottom',true);this.addField_SFBool(ctx,'side',true);this.addField_SFBool(ctx,'top',true);this.addField_SFFloat(ctx,'subdivision',32);var geoCacheID='Cone_'+this._vf.bottomRadius+'_'+this._vf.height+'_'+this._vf.top+'_'+ this._vf.bottom+'_'+this._vf.side+'_'+this._vf.topRadius+'_'+this._vf.subdivision;if(this._vf.useGeoCache&&x3dom.geoCache[geoCacheID]!==undefined){this._mesh=x3dom.geoCache[geoCacheID];} else{var bottomRadius=this._vf.bottomRadius,height=this._vf.height;var topRadius=this._vf.topRadius,sides=this._vf.subdivision;var beta,x,z;var delta=2.0*Math.PI/sides;var incl=(bottomRadius-topRadius)/height;var nlen=1.0/Math.sqrt(1.0+incl*incl);var j=0,k=0;var h,base;if(this._vf.side&&height>0){var px=0,pz=0;for(j=0,k=0;j<=sides;j++){beta=j*delta;x=Math.sin(beta);z=-Math.cos(beta);if(topRadius>x3dom.fields.Eps){px=x*topRadius;pz=z*topRadius;} this._mesh._positions[0].push(px,height/2,pz);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,1);this._mesh._positions[0].push(x*bottomRadius,-height/2,z*bottomRadius);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,0);if(j>0){this._mesh._indices[0].push(k);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+3);k+=2;}}} if(this._vf.bottom&&bottomRadius>0){base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=bottomRadius*Math.sin(beta);z=-bottomRadius*Math.cos(beta);this._mesh._positions[0].push(x,-height/2,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/bottomRadius/2+0.5,z/bottomRadius/2+0.5);} h=base+1;for(j=2;jx3dom.fields.Eps){base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=topRadius*Math.sin(beta);z=-topRadius*Math.cos(beta);this._mesh._positions[0].push(x,height/2,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/topRadius/2+0.5,1.0-z/topRadius/2+0.5);} h=base+1;for(j=2;j0) {var px=0,pz=0;for(j=0,k=0;j<=sides;j++){beta=j*delta;x=Math.sin(beta);z=-Math.cos(beta);if(topRadius>x3dom.fields.Eps){px=x*topRadius;pz=z*topRadius;} this._mesh._positions[0].push(px,height/2,pz);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,1);this._mesh._positions[0].push(x*bottomRadius,-height/2,z*bottomRadius);this._mesh._normals[0].push(x/nlen,incl/nlen,z/nlen);this._mesh._texCoords[0].push(1.0-j/sides,0);if(j>0){this._mesh._indices[0].push(k);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+3);k+=2;}}} if(this._vf.bottom&&bottomRadius>0) {base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=bottomRadius*Math.sin(beta);z=-bottomRadius*Math.cos(beta);this._mesh._positions[0].push(x,-height/2,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/bottomRadius/2+0.5,z/bottomRadius/2+0.5);} h=base+1;for(j=2;jx3dom.fields.Eps) {base=this._mesh._positions[0].length/3;for(j=sides-1;j>=0;j--){beta=j*delta;x=topRadius*Math.sin(beta);z=-topRadius*Math.cos(beta);this._mesh._positions[0].push(x,height/2,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/topRadius/2+0.5,1.0-z/topRadius/2+0.5);} h=base+1;for(j=2;j0) {this._mesh._indices[0].push(k);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+3);k+=2;}}} if(radius>0) {var h,base=this._mesh._positions[0].length/3;if(this._vf.top) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,height,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,-z/radius/2+0.5);} h=base+1;for(j=2;j=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,-height,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,z/radius/2+0.5);} h=base+1;for(j=2;j0) {var h,base=this._mesh._positions[0].length/3;if(this._vf.top) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,height,z);}}} if(this._vf.bottom) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,-height,z);}} this.invalidateVolume();this._mesh._numCoords=this._mesh._positions[0].length/3;Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;node.invalidateVolume();});} else if(fieldName==="subdivision"||fieldName==="bottom"||fieldName==="top"||fieldName==="side") {this._mesh._positions[0]=[];this._mesh._indices[0]=[];this._mesh._normals[0]=[];this._mesh._texCoords[0]=[];var radius=this._vf.radius,height=this._vf.height/2;var sides=this._vf.subdivision;var beta,x,z,j;var delta=2.0*Math.PI/sides;var k=0;if(this._vf.side) {for(j=0,k=0;j<=sides;j++) {beta=j*delta;x=Math.sin(beta);z=-Math.cos(beta);this._mesh._positions[0].push(x*radius,-height,z*radius);this._mesh._normals[0].push(x,0,z);this._mesh._texCoords[0].push(1.0-j/sides,0);this._mesh._positions[0].push(x*radius,height,z*radius);this._mesh._normals[0].push(x,0,z);this._mesh._texCoords[0].push(1.0-j/sides,1);if(j>0) {this._mesh._indices[0].push(k+0);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+2);this._mesh._indices[0].push(k+1);this._mesh._indices[0].push(k+3);k+=2;}}} if(radius>0) {var h,base=this._mesh._positions[0].length/3;if(this._vf.top) {for(j=sides-1;j>=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,height,z);this._mesh._normals[0].push(0,1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,-z/radius/2+0.5);} h=base+1;for(j=2;j=0;j--) {beta=j*delta;x=radius*Math.sin(beta);z=-radius*Math.cos(beta);this._mesh._positions[0].push(x,-height,z);this._mesh._normals[0].push(0,-1,0);this._mesh._texCoords[0].push(x/radius/2+0.5,z/radius/2+0.5);} h=base+1;for(j=2;j=this._vf['url'].length) {return;} var currentURL=shape._nameSpace.getURL(this._vf['url'][this._currentURLIdx]);var urlSuffix=currentURL.substr(currentURL.lastIndexOf('.'));if(urlSuffix.substr(0,4)=='.src') {var srcUsedWarnMessage="Legacy SRC format used for content for \""+currentURL+"\". "+"It is recommended to use a binary-glTF-conformant .glb container instead.";x3dom.debug.logWarning(srcUsedWarnMessage);console.warn(srcUsedWarnMessage);ExternalGeometrySRC.updateRenderData(shape,shaderProgram,gl,viewarea,context,this._mesh,this._vf['url'],this._currentURLIdx);return;} if(x3dom.BinaryContainerLoader.outOfMemory){return;} shape._webgl.internalDownloadCount=1;shape._nameSpace.doc.incrementDownloads();xhr=new XMLHttpRequest();var encoding=(currentURL.indexOf(".glb")!=-1)?"binary":"ascii";var xhr=new XMLHttpRequest();xhr.open("GET",this._nameSpace.getURL(this._vf['url'][this._currentURLIdx]),true);xhr.responseType=(encoding=="binary")?"arraybuffer":"json";x3dom.RequestManager.addRequest(xhr);xhr.onerror=function(){x3dom.debug.logError("Unable to load GLB data from URL \""+currentURL+"\"");};xhr.onload=function(){shape._webgl.internalDownloadCount=0;shape._nameSpace.doc.decrementDownloads();shape._webgl.primType=[];shape._webgl.indexOffset=[];shape._webgl.drawCount=[];if((xhr.status==200||xhr.status==0)){var glTF=new x3dom.glTF.glTFLoader(true);glTF.load(xhr.response,function() {if(glTF.header.sceneLength>0) {glTF.loaded={};glTF.loaded.meshes={};glTF.loaded.meshCount=0;if(currentURL.includes('#')) {var split=currentURL.split('#');var meshName=split[split.length-1];glTF.getMesh(shape,shaderProgram,gl,meshName);} else {glTF.getScene(shape,shaderProgram,gl);} for(var key in glTF._mesh){if(!glTF._mesh.hasOwnProperty(key))continue;that._mesh[key]=glTF._mesh[key];}} else {if((that._currentURLIdx+1)=urls.length) {return;} if(x3dom.BinaryContainerLoader.outOfMemory){return;} shape._webgl.internalDownloadCount=1;shape._nameSpace.doc.incrementDownloads();xhr=new XMLHttpRequest();xhr.open("GET",shape._nameSpace.getURL(urls[currentURLIndex]),true);xhr.responseType="arraybuffer";xhr.send(null);xhr.onerror=function(){x3dom.debug.logError("Unable to load SRC data from URL \""+urls[currentURLIndex]+"\"");};xhr.onload=function(){shape._webgl.internalDownloadCount=0;shape._nameSpace.doc.decrementDownloads();var responseBeginUint32=new Uint32Array(xhr.response,0,12);var srcHeaderSize,srcBodySize,srcBodyOffset;var srcHeaderView,srcBodyView;var srcHeaderObj;if((xhr.status==200||xhr.status==0)&&responseBeginUint32.length>=3){srcHeaderSize=responseBeginUint32[2];srcBodyOffset=srcHeaderSize+12;srcBodySize=xhr.response.byteLength-srcBodyOffset;if(srcHeaderSize>0&&srcBodySize>=0) {srcHeaderView=new Uint8Array(xhr.response,12,srcHeaderSize);srcBodyView=new Uint8Array(xhr.response,srcBodyOffset,srcBodySize);try {srcHeaderObj=JSON.parse(String.fromCharCode.apply(null,srcHeaderView));} catch(exc) {x3dom.debug.logError("Unable to parse SRC header: "+exc);return;} ExternalGeometrySRC._updateRenderDataFromSRC(shape,shaderProgram,gl,srcHeaderObj,srcBodyView,x3domMesh);} else {if((currentURLIndex+1)=0);return(this._vf.lit&&hasTris);}}));x3dom.registerNodeType("BinaryGeometry","Geometry3D",defineClass(x3dom.nodeTypes.X3DBinaryContainerGeometryNode,function(ctx){x3dom.nodeTypes.BinaryGeometry.superClass.call(this,ctx);this.addField_SFString(ctx,'index',"");this.addField_SFString(ctx,'coord',"");this.addField_SFString(ctx,'normal',"");this.addField_SFString(ctx,'texCoord',"");this.addField_SFString(ctx,'color',"");this.addField_SFString(ctx,'tangent',"");this.addField_SFString(ctx,'binormal',"");this.addField_SFString(ctx,'indexType',"Uint16");this.addField_SFString(ctx,'coordType',"Float32");this.addField_SFString(ctx,'normalType',"Float32");this.addField_SFString(ctx,'texCoordType',"Float32");this.addField_SFString(ctx,'colorType',"Float32");this.addField_SFString(ctx,'tangentType',"Float32");this.addField_SFString(ctx,'binormalType',"Float32");this.addField_SFBool(ctx,'normalAsSphericalCoordinates',false);this.addField_SFBool(ctx,'rgbaColors',false);this.addField_SFInt32(ctx,'numTexCoordComponents',2);this.addField_SFBool(ctx,'normalPerVertex',true);this.addField_SFBool(ctx,'idsPerVertex',false);this.addField_SFBool(ctx,'compressed',false);this._hasStrideOffset=false;this._mesh._numPosComponents=this._vf.normalAsSphericalCoordinates?4:3;this._mesh._numTexComponents=this._vf.numTexCoordComponents;this._mesh._numColComponents=this._vf.rgbaColors?4:3;this._mesh._numNormComponents=this._vf.normalAsSphericalCoordinates?2:3;this._vertexCountSum=0;for(var i=0;i=0&&strideInd>=0){offset=+this._vf.coord.substring(++offsetInd,strideInd);stride=+this._vf.coord.substring(strideInd);parent._coordStrideOffset=[stride,offset];this._hasStrideOffset=true;if((offset/8)-Math.floor(offset/8)==0){this._mesh._numPosComponents=4;}} else if(strideInd>=0){stride=+this._vf.coord.substring(strideInd);parent._coordStrideOffset=[stride,0];if((stride/8)-Math.floor(stride/8)==0){this._mesh._numPosComponents=4;}} offsetInd=this._vf.normal.lastIndexOf('#');strideInd=this._vf.normal.lastIndexOf('+');if(offsetInd>=0&&strideInd>=0){offset=+this._vf.normal.substring(++offsetInd,strideInd);stride=+this._vf.normal.substring(strideInd);parent._normalStrideOffset=[stride,offset];} else if(strideInd>=0){stride=+this._vf.normal.substring(strideInd);parent._normalStrideOffset=[stride,0];} offsetInd=this._vf.texCoord.lastIndexOf('#');strideInd=this._vf.texCoord.lastIndexOf('+');if(offsetInd>=0&&strideInd>=0){offset=+this._vf.texCoord.substring(++offsetInd,strideInd);stride=+this._vf.texCoord.substring(strideInd);parent._texCoordStrideOffset=[stride,offset];} else if(strideInd>=0){stride=+this._vf.texCoord.substring(strideInd);parent._texCoordStrideOffset=[stride,0];} offsetInd=this._vf.color.lastIndexOf('#');strideInd=this._vf.color.lastIndexOf('+');if(offsetInd>=0&&strideInd>=0){offset=+this._vf.color.substring(++offsetInd,strideInd);stride=+this._vf.color.substring(strideInd);parent._colorStrideOffset=[stride,offset];} else if(strideInd>=0){stride=+this._vf.color.substring(strideInd);parent._colorStrideOffset=[stride,0];} if(this._vf.indexType!="Uint16"&&!x3dom.caps.INDEX_UINT) x3dom.debug.logWarning("Index type "+this._vf.indexType+" problematic");},doIntersect:function(line) {var min=this.getMin();var max=this.getMax();var isect=line.intersect(min,max);if(isect&&line.enterthis._vf.bbMaxModF.x) this._vf.bbShiftVec.x=1.0;if(this._vf.bbMinModF.y>this._vf.bbMaxModF.y) this._vf.bbShiftVec.y=1.0;if(this._vf.bbMinModF.z>this._vf.bbMaxModF.z) this._vf.bbShiftVec.z=1.0;this.addField_MFNode('levels',x3dom.nodeTypes.PopGeometryLevel);this.addField_SFInt32(ctx,'attributeStride',0);this.addField_SFInt32(ctx,'positionOffset',0);this.addField_SFInt32(ctx,'normalOffset',0);this.addField_SFInt32(ctx,'texcoordOffset',0);this.addField_SFInt32(ctx,'colorOffset',0);this.addField_SFInt32(ctx,'numAnchorVertices',0);this.addField_SFInt32(ctx,'positionPrecision',2);this.addField_SFInt32(ctx,'normalPrecision',1);this.addField_SFInt32(ctx,'texcoordPrecision',2);this.addField_SFInt32(ctx,'colorPrecision',1);this.addField_SFInt32(ctx,'minPrecisionLevel',-1);this.addField_SFInt32(ctx,'maxPrecisionLevel',-1);this.addField_SFFloat(ctx,'precisionFactor',1.0);this.addField_SFString(ctx,'coordType',"Uint16");this.addField_SFString(ctx,'normalType',"Uint8");this.addField_SFString(ctx,'texCoordType',"Uint16");this.addField_SFString(ctx,'colorType',"Uint8");this.addField_SFInt32(ctx,'vertexBufferSize',0);this.addField_SFBool(ctx,'indexedRendering',true);this.addField_SFBool(ctx,'sphericalNormals',false);this.addField_MFInt32(ctx,'originalVertexCount',[0]);for(var i=0;i0){var geoCacheID='ImageGeometry_'+this._vf.implicitMeshSize.x+'_'+this._vf.implicitMeshSize.y;if(this._vf.useGeoCache&&x3dom.geoCache[geoCacheID]!==undefined) {this._mesh=x3dom.geoCache[geoCacheID];} else {for(var y=0;y0) {hasNormalInd=true;} if(texCoordInd.length>0) {hasTexCoordInd=true;} if(colorInd.length>0) {hasColorInd=true;} var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode.getPoints();var normalNode=this._cf.normal.node;if(normalNode) {hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode) {if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(!hasTexCoordInd) {var i,lastTexCoord=texCoords.length;for(i=lastTexCoord;ix3dom.Utils.maxIndexableCoords)||(hasNormal&&hasNormalInd)||(hasTexCoord&&hasTexCoordInd)||(hasColor&&hasColorInd)) {if(this._vf.creaseAngle<=x3dom.fields.Eps) x3dom.debug.logWarning('Fallback to inefficient multi-index mode since creaseAngle=0.');if(this._vf.convex){t=0;cnt=0;faceCnt=0;this._mesh._multiIndIndices=[];this._mesh._posSize=positions.length;for(i=0;i0) this._mesh._numFaces+=indexLength/3;else this._mesh._numFaces+=numCoords/3;}},fieldChanged:function(fieldName) {if(fieldName!="coord"&&fieldName!="normal"&&fieldName!="texCoord"&&fieldName!="color"&&fieldName!="coordIndex") {x3dom.debug.logWarning("IndexedFaceSet: fieldChanged for "+ fieldName+" not yet implemented!");return;} var pnts=this._cf.coord.node._vf.point;var n=pnts.length;var texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(((this._vf.creaseAngle<=x3dom.fields.Eps)||(n>x3dom.Utils.maxIndexableCoords)||(this._vf.normalIndex.length>0&&this._cf.normal.node)||(this._vf.texCoordIndex.length>0&&texCoordNode)||(this._vf.colorIndex.length>0&&this._cf.color.node))&&this._mesh._multiIndIndices) {var needNormals=!this._cf.normal.node&&this._vf.normalUpdateMode.toLowerCase()!='none';n=this._mesh._multiIndIndices.length;this._mesh._positions[0]=[];this._mesh._indices[0]=[];if(fieldName=="coord"&&n) {if(needNormals){this._mesh._normals[0]=[];} for(i=0;i0) {hasNormalInd=true;} if(texCoordInd.length>0) {hasTexCoordInd=true;} if(colorInd.length>0) {hasColorInd=true;} var positions,normals,texCoords,colors;var coordNode=this._cf.coord.node;x3dom.debug.assert(coordNode);positions=coordNode.getPoints();var normalNode=this._cf.normal.node;if(normalNode) {hasNormal=true;normals=normalNode._vf.vector;} else{hasNormal=false;} var texMode="",numTexComponents=2;texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} if(texCoordNode) {if(texCoordNode._vf.point){hasTexCoord=true;texCoords=texCoordNode._vf.point;if(!hasTexCoordInd) {var i,lastTexCoord=texCoords.length;for(i=lastTexCoord;i0) this._mesh._numFaces+=indexLength/3;else this._mesh._numFaces+=numCoords/3;} Array.forEach(this._parentNodes,function(node){node.setGeoDirty();});} else{if(fieldName=="coord") {var needNormals=!this._cf.normal.node&&this._vf.normalUpdateMode.toLowerCase()!='none';this._mesh._positions[0]=pnts.toGL();if(needNormals){this._mesh.calcNormals(this._vf.creaseAngle,this._vf.ccw);} this.invalidateVolume();Array.forEach(this._parentNodes,function(node){node._dirty.positions=true;if(needNormals) node._dirty.normals=true;node.invalidateVolume();});} else if(fieldName=="color") {pnts=this._cf.color.node._vf.color;this._mesh._colors[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.colors=true;});} else if(fieldName=="normal") {pnts=this._cf.normal.node._vf.vector;this._mesh._normals[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.normals=true;});} else if(fieldName=="texCoord") {texCoordNode=this._cf.texCoord.node;if(x3dom.isa(texCoordNode,x3dom.nodeTypes.MultiTextureCoordinate)){if(texCoordNode._cf.texCoord.nodes.length) texCoordNode=texCoordNode._cf.texCoord.nodes[0];} pnts=texCoordNode._vf.point;this._mesh._texCoords[0]=pnts.toGL();Array.forEach(this._parentNodes,function(node){node._dirty.texcoords=true;});} else if(fieldName=="coordIndex") {needNormals=!this._cf.normal.node&&this._vf.normalUpdateMode.toLowerCase()!='none';indexes=this._vf.coordIndex;t=0;n=indexes.length;this._mesh._indices[0]=[];for(i=0;i=0.0){alpha_1=(-B+Math.sqrt(determinant))/(2.0*A);alpha_2=(-B-Math.sqrt(determinant))/(2.0*A);alpha_1=Math.min(alpha_1,alpha_2);if(alpha_1>=1.0){var hitPoint=viewRay.pos.add(viewRay.dir.multiply(alpha_1));var vecToHitPoint=hitPoint.subtract(this._localOrigin).normalize();this._currentRotation=x3dom.fields.Quaternion.rotateFromTo(this._initialSphereIntersectionVector,vecToHitPoint);this._currentRotation=this._currentRotation.multiply(this._vf.offset);this.postMessage('rotation_changed',this._currentRotation);}} else{}},_stopDragging:function() {x3dom.nodeTypes.X3DDragSensorNode.prototype._stopDragging.call(this);if(this._vf.autoOffset) {this._vf.offset=this._currentRotation;this.postMessage('offset_changed',this._vf.offset);} this._currentRotation=new x3dom.fields.Quaternion();}}));x3dom.registerNodeType("CylinderSensor","PointingDeviceSensor",defineClass(x3dom.nodeTypes.X3DDragSensorNode,function(ctx) {x3dom.nodeTypes.CylinderSensor.superClass.call(this,ctx);this.addField_SFFloat(ctx,'offset',0);this.addField_SFRotation(ctx,'axisRotation',0,1,0,0);this.addField_SFFloat(ctx,'diskAngle',0.262);this.addField_SFFloat(ctx,'minAngle',0);this.addField_SFFloat(ctx,'maxAngle',-1);this._rotationMatrix=this._vf.axisRotation.toMatrix();this._inverseToWorldMatrix=null;this._initialCylinderIntersectionVector=null;this._viewArea=null;this._cylinderRadius=0.0;this._yAxisLine=null;this._cylinderMode=true;this._currentRotationAngle=0.0;},{getCurrentTransform:function() {var parentTransform=x3dom.nodeTypes.X3DDragSensorNode.prototype.getCurrentTransform.call(this);return parentTransform.mult(this._rotationMatrix);},_startDragging:function(viewarea,x,y,wx,wy,wz) {x3dom.nodeTypes.X3DDragSensorNode.prototype._startDragging.call(this,viewarea,x,y,wx,wy,wz);this._currentRotation=new x3dom.fields.Quaternion();this._viewArea=viewarea;this._yAxisLine=new x3dom.fields.Line(new x3dom.fields.SFVec3f(0.0,0.0,0.0),new x3dom.fields.SFVec3f(0.0,1.0,0.0));this._inverseToWorldMatrix=this.getCurrentTransform().inverse();var firstIntersection=this._inverseToWorldMatrix.multMatrixPnt(new x3dom.fields.SFVec3f(wx,wy,wz));var closestPointOnYAxis=this._yAxisLine.closestPoint(firstIntersection);this._initialCylinderIntersectionVector=firstIntersection.subtract(closestPointOnYAxis);this._cylinderRadius=this._initialCylinderIntersectionVector.length();this._initialCylinderIntersectionVector=this._initialCylinderIntersectionVector.normalize();},_process2DDrag:function(x,y,dx,dy) {x3dom.nodeTypes.X3DDragSensorNode.prototype._process2DDrag.call(this,x,y,dx,dy);if(this._cylinderMode) {var viewRay=this._viewArea.calcViewRay(x,y);viewRay.pos=this._inverseToWorldMatrix.multMatrixPnt(viewRay.pos);viewRay.dir=this._inverseToWorldMatrix.multMatrixVec(viewRay.dir);var A=viewRay.dir.subtract(this._yAxisLine.dir.multiply(viewRay.dir.dot(this._yAxisLine.dir)));var B=viewRay.pos.subtract(this._yAxisLine.pos).add(this._yAxisLine.dir.multiply(this._yAxisLine.dir.dot(this._yAxisLine.pos.subtract(viewRay.pos))));var p=2*A.dot(B)/A.dot(A);var q=(B.dot(B)-this._cylinderRadius*this._cylinderRadius)/A.dot(A);var sqrt_part=p*p*0.25-q;var alpha_1;var alpha_2;if(sqrt_part>=0) {sqrt_part=Math.sqrt(sqrt_part);alpha_1=-p*0.5+sqrt_part;alpha_2=-p*0.5-sqrt_part;alpha_1=Math.min(alpha_1,alpha_2);if(alpha_1>0.0) {var hitPoint=viewRay.pos.add(viewRay.dir.multiply(alpha_1));var closestPointOnYAxis=this._yAxisLine.closestPoint(hitPoint);var vecToHitPoint=hitPoint.subtract(closestPointOnYAxis).normalize();this._currentRotation=x3dom.fields.Quaternion.rotateFromTo(this._initialCylinderIntersectionVector,vecToHitPoint);var offsetQuat=x3dom.fields.Quaternion.axisAngle(this._yAxisLine.dir,this._vf.offset);this._currentRotation=this._currentRotation.multiply(offsetQuat);this.postMessage('rotation_changed',this._currentRotation);}}} else {}},_stopDragging:function() {x3dom.nodeTypes.X3DDragSensorNode.prototype._stopDragging.call(this);if(this._vf.autoOffset) {this._vf.offset=this._currentRotation.angle();this.postMessage('offset_changed',this._vf.offset);}}}));x3dom.registerNodeType("X3DSequencerNode","EventUtilities",defineClass(x3dom.nodeTypes.X3DChildNode,function(ctx){x3dom.nodeTypes.X3DSequencerNode.superClass.call(this,ctx);this.addField_SFBool(ctx,'next',false);this.addField_SFBool(ctx,'previous',false);this.addField_MFFloat(ctx,'key',[]);this.addField_SFFloat(ctx,'set_fraction',0);this._keyIndex=-1;this._key_changed=false;this._keyValue_changed=false;},{findInterval:function(time){var keyLength=this._vf.key.length-1;if(time=this._vf.key[keyLength]){return keyLength;} for(var i=0;i